-
int to char array?
What is the best way to go about converting a 4-byte integer into a char array such that each element of the array contains a byte from the integer?
For example: I have an integer, 56, which looks like this in memory: 0x00 0x00 0x00 0x38. I want to convert that integer to an array of chars, with array[0] = 0x00 ... array[3] = 0x38.
I've tried memcpy() to copy the memory directly from the integer, and it works to an extent, but it doesn't seem to like int values over 128 (max size for a char), which makes me think that memcpy() is trying to copy the entire int into the first element of the array, which is obviously not what I want.
I've also tried using a char pointer to access each byte of the integer individually, but I get the same problem.
Any suggestions?
-
Maybe you could post what you have tried. You certainly CAN copy an integer to a char array. Also note that values over 128 will be negative in an array of signed char.
--
Mats
-
What happens with values over 128?
Shouldn't you use an unsigned char* buffer instead?
-
Better try using unsigned char.
-
The code I'm working with is this:
Code:
int number = 500;
char charArray[4];
bzero( charArray, 4 );
memcpy( charArray, &number, 4 );
int i;
for( i = 0; i < 4; ++i ) {
printf( "charArray[%d]: %02X\n" );
}
I get this as output:
00 00 01 FFFFFFF4
-
I'm trying to find the emoticon that shows me slapping myself upside the head.
Using an unsigned char buffer fixed the problem. Thanks everyone.
-
That's not your actual code, right? Because that would print random rubbish, since there's no arguments for printf.
Yes, that's because %x shows the number as an unsigned, and char values passed to printf are converted to int before they are passed along. You can, as suggested, use unsigned char, or you could do something like this:
Code:
printf( "charArray[%d]: %02X\n", i, ((int)charArray[i]) & 0xff);
And it's completely unnecessary to use bzero() immediately before memcpy(), since memcpy() will overwrite your zero's with the value from the integer.
--
Mats
-
Whoops, just forgot to add the args when typing it (it's not actual code, just the general idea of what I was doing).
Good point about bzero(). Not sure what I was thinking there.
-
Note that you could achieve the same affect as the bzero call like this.
Code:
char charArray[4] = {0};
Assuming you needed it, of course.