Possible Duplicate:
Converting an int into a 4 byte char array (C)
Using the Dynamic C program (the language is C), I am trying to convert an int into an array of bytes 4 places long. So far I have looked online and I have found a few examples. However, none seem to work for me. I have had an ongoing problem where the correct byte numbers are printed, but they are repeated twice for some reason. I have provided the code below:
void main(){
int a=1379;
int i=0;
unsigned char value [4];
value[3] = (byte) (a & (0xFF));
value[2] = (byte) ((a >> 8) & 0xFF);
value[1] = (byte) ((a >> 16) & 0xFF);
value[0] = (byte) ((a >> 24) & 0xFF);
//convert int values to bytes by placing them in a char buffer
for(i=0;i<4;i++){
printf("%d",value[i]);
printf(", ");
}
printf("\n");
}
For example, with this value the program prints “5, 99, 5, 99,” when it should print “0, 0, 5, 99”. Thank you for your help.
It’s almost certainly the case that “Dynamic C” is an implementation with an
intof 16 bits, which is perfectly “legal” for C. If theintis 16 bits, any shift over 16 bits is modulo-16, so the second two shifts duplicate the first two.