Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

One 32bit Long into 4 8bit Chars

Name: Anonymous 2010-06-28 7:43

In C code

I'm gonna ask a stupid question here, but I'm not sure I trust my code so I want to hear if you can tell me what's wrong with my approach

Right now, the code goes

long data

char data0
char data1
char data2
char data3

data0 = data;
data1 = data >> 8;
data2 = data >> 16;
data3 = data >> 24;

but I'm not sure that's the best approach, or even a good approach. It works, which is most important obviously, but I have this nagging feeling that there's something very not Best Practices about this approach and I can't shake that feeling.

Name: Anonymous 2010-06-28 17:14

>>1
Wow, /prog/ as usual has been tremendously unhelpful to you. Your original solution is already perfectly correct. Bit shift works as expected regardless of endianness, and casting it always keeps the least significant bits. The only thing I would recommend is to explicitly cast the results, otherwise you will get warnings about a loss of precision (you should turn on more compiler warnings.) You may also want to use unsigned char or uint8_t instead of char.

unsigned char data0 = (unsigned char)data;
unsigned char data1 = (unsigned char)(data >> 8);

etc.

Incidentally, to get the chars back into a long, you do just the opposite. Just make sure the chars are unsigned, otherwise casting it to long will carry the sign bit. Here I explicitly cast the chars to unsigned:

data = ((long)(unsigned char)data0) | (((long)(unsigned char)data1) << 8) | (((long)(unsigned char)data2) << 16) | (((long)(unsigned char)data3) << 24)

DO NOT USE A UNION like everyone here has been saying, and do not type-pun a pointer to a char array either. It's not portable, and it won't work on little-endian machines (i.e. x86). Combining it with htonl() is just making a bad solution worse. Honestly I'm surprised how many people are suggesting that garbage.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List