Converting an int into a 4 byte char array (C) -
Converting an int into a 4 byte char array (C) -
hey, i'm looking convert int inputed user 4 bytes, assigning character array. how can done?
example:
convert user inputs of 175 to
00000000 00000000 00000000 10101111
issue of answers far, converting 255 should result in 0 0 0 ff
although 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 illustration 175 input prints out 0, 0, 0, ffffffaf
when should 0, 0, 0, af
the portable way (ensuring 0x00 0x00 0x00 0xaf
everywhere) utilize shifts:
unsigned char bytes[4]; unsigned long n = 175; bytes[0] = (n >> 24) & 0xff; bytes[1] = (n >> 16) & 0xff; bytes[2] = (n >> 8) & 0xff; bytes[3] = n & 0xff;
the methods using unions , memcpy()
different result on different machines.
the issue having printing rather conversion. presume using char
rather unsigned char
, , using line print it:
printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);
when types narrower int
passed printf
, promoted int
(or unsigned int
, if int
cannot hold values of original type). if char
signed on platform, 0xff
not fit range of type, , beingness set -1 instead (which has representation 0xff
on 2s-complement machine).
-1 promoted int
, , has representation 0xffffffff
int
on machine, , see.
your solution either utilize unsigned char
, or else cast unsigned char
in printf
statement:
printf("%x %x %x %x\n", (unsigned char)bytes[0], (unsigned char)bytes[1], (unsigned char)bytes[2], (unsigned char)bytes[3]);
c
Comments
Post a Comment