Hey, I’m looking to convert a int that is inputed by the user into 4 bytes, that I am assigning to a character array. How can this be done?
Example:
Convert a user inputs of 175 to
00000000 00000000 00000000 10101111
Issue with all of the answers so far, converting 255 should result in 0 0 0 ff although it prints out as: 0 0 0 ffffffff
unsigned int value = 255;
buffer[0] = (value >> 24) & 0xFF;
buffer[1] = (value >> 16) & 0xFF;
buffer[2] = (value >> 8) & 0xFF;
buffer[3] = value & 0xFF;
union {
unsigned int integer;
unsigned char byte[4];
} temp32bitint;
temp32bitint.integer = value;
buffer[8] = temp32bitint.byte[3];
buffer[9] = temp32bitint.byte[2];
buffer[10] = temp32bitint.byte[1];
buffer[11] = temp32bitint.byte[0];
both result in 0 0 0 ffffffff instead of 0 0 0 ff
Just another example is 175 as the input prints out as 0, 0, 0, ffffffaf when it should just be 0, 0, 0, af
The portable way to do this (ensuring that you get
0x00 0x00 0x00 0xafeverywhere) is to use shifts:The methods using unions and
memcpy()will get a different result on different machines.The issue you are having is with the printing rather than the conversion. I presume you are using
charrather thanunsigned char, and you are using a line like this to print it:When any types narrower than
intare passed toprintf, they are promoted toint(orunsigned int, ifintcannot hold all the values of the original type). Ifcharis signed on your platform, then0xfflikely does not fit into the range of that type, and it is being set to -1 instead (which has the representation0xffon a 2s-complement machine).-1 is promoted to an
int, and has the representation0xffffffffas aninton your machine, and that is what you see.Your solution is to either actually use
unsigned char, or else cast tounsigned charin theprintfstatement: