In the bit-shifting example shown
here:
unsigned long int longInt = 1234567890;
unsigned char byteArray[4];
// convert from an unsigned long int to a 4-byte array
byteArray[0] = (int)((longInt >> 24) & 0xFF) ;
byteArray[1] = (int)((longInt >> 16) & 0xFF) ;
byteArray[2] = (int)((longInt >> 8) & 0XFF);
byteArray[3] = (int)((longInt & 0XFF));
Three questions:
- Why is it (int) instead of (unsigned char)? I tried it with unsigned char and it seems to compile just fine.
- Is 0XFF necessary? Isn’t the new bit shifted-in 0 because Wikipedia says C uses logical shifting and logical shifting shifts in 0? (EDIT: at least it doesn’t seem necessary on one with >> 24?)
- Can’t I just do a memcpy() to copy longInt to a unsigned char buffer? Is it not so because of issue with Endianness? Is there any other reason?
1.
((longInt >> 24) & 0xFF)expression is of typeunsigned long int. With the cast tointthe expression is first converted tointthen tounsigned char. If you don’t cast tointthe expression is not first converted toint. There are no difference in the two situations and the cast is superfluous.2.
The
0xffis not necessary. The conversion tounsigned charactually performs the same.3.
You can use
memcpybut it is not portable because it depends on the endianness of the system. It will give different results if the system is big endian or little endian while the bitwise shift solution will give the same results.