LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Accessing the low and high bytes of a short integer (C)? (https://www.linuxquestions.org/questions/programming-9/accessing-the-low-and-high-bytes-of-a-short-integer-c-4175474481/)

stf92 08-23-2013 11:12 PM

Accessing the low and high bytes of a short integer (C)?
 
Hi:
Is there a way to access the low and high bytes of a short integer in C? I am doing
Code:

unsigned short chk;
unsigned char* _chk= &chk;

chk=0x1234;
printf("High byte= %x low byte= %x\n", _chk[0], _chk[1]);

But there must be an easier way to do it. Something like low(chk), high(chk). It's a question.

firstfire 08-23-2013 11:24 PM

Hi.

Code:

#define LOW(x) (x&0xFF)
#define HIG(x) LOW((x>>8))


stf92 08-23-2013 11:31 PM

Quote:

Originally Posted by firstfire (Post 5014834)
Hi.

Code:

#define LOW(x) (x&0xFF)
#define HIG(x) LOW((x>>8))


I don't get it. If x=0x1234, then LOW = 34 and HIG = 00.

stf92 08-23-2013 11:48 PM

Now I see. But is not #define HIG(x) x>>8 enough?

firstfire 08-24-2013 12:02 AM

Quote:

Originally Posted by stf92 (Post 5014840)
Now I see. But is not #define HIG(x) x>>8 enough?

Imagine that you have 4-byte number as input.
EDIT: And never omit parentheses in macros! What if you wanted to compute HIG(x+1)?

stf92 08-24-2013 01:05 AM

Yes, that is a thing I learned time ago. But I insist: if the number is
Code:

unsigned short x;
then, if x = 0x1234, x >> 8 should give me 0x12. Now if it declared as integer, well, integer could be 4 or 8 bytes, I see the point here. Thanks for your reply.

H_TeXMeX_H 08-24-2013 01:41 AM

Why not just use set width types in stdint.h. I tend to do that now for everything but counters (unsigned int or long).

stf92 08-24-2013 01:46 AM

Quote:

Originally Posted by H_TeXMeX_H (Post 5014883)
Why not just use set width types in stdint.h. I tend to do that now for everything but counters (unsigned int or long).

How do you use it?

H_TeXMeX_H 08-24-2013 03:20 AM

Code:

#include <stdio.h>
#include <stdint.h>

#define LOW(x) ((x) & 0xff)
#define HIGH(x) ((x) >> 8)

int main (void)
{
        uint16_t chk = 0x1234;

        printf ("%02x %02x\n", HIGH (chk), LOW (chk));

        return 0;
}


stf92 08-24-2013 03:23 AM

Thank you very much, TeXMeX.


All times are GMT -5. The time now is 05:48 AM.