Help! C question

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
Here's the problem:

Given: 32-bit integer
Output: byte array of integer. (assume a byte data type exists)

For example, given the number 1000 in decimal. In Hex it is 0000 0000 0000 1388. As an output, I want an array of bytes = 00 00 00 00 00 00 13 88.

Here would be the signature:

byte * int_to_byte_array( int n)

Sound easy? One catch, you can't use masks or bit shifting. So, you have to do some clever casting. I can't seem to get the right combination going.

Any help?
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
byte *int_to_byte_array(int n)
{
return &n;
}


edit: WARNING: the endian-ness of the CPU you're running on WILL affect the result. x86 machines are "little-endian", the vast majority of the universe uses easier-to-understand-as-a-human-and-no-harder-to-implement-as-a-cpu-designer "big-endian". This means if your number was, in hex, 0x12345678, an x86 machine would store it in memory as 78 56 34 12, while most every other type would store it as 12 34 56 78.
 

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
Originally posted by: CTho9305
byte *int_to_byte_array(int n)
{
return &n;
}


edit: WARNING: the endian-ness of the CPU you're running on WILL affect the result. x86 machines are "little-endian", the vast majority of the universe uses easier-to-understand-as-a-human-and-no-harder-to-implement-as-a-cpu-designer "big-endian". This means if your number was, in hex, 0x12345678, an x86 machine would store it in memory as 78 56 34 12, while most every other type would store it as 12 34 56 78.

hmm... I thought that was all to it too. But, my program doesn't seem to be working. At least I have confirmation on how to do it now.

Thanks for the warning on endian-ness. I didn't think about it at all. :beer:
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
hmmm. On second thought, it might be better if you passed n in by reference, or did a "int temp = new int; *temp = n; return &temp" (remember to delete/free it later). You have to remember that if n goes out of scope or is otherwise modified, the return value of the function won't be very useful.
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
In your problem statement you seem to be saying you want a 32-bit int conversted to an 8-byte array of hex values, not just a 4-byte. Casting can convert to a 4-byte array but won't split bytes for you.

CTho9305's code is about right (if you did want a 4-byte value not 8) except for passing by value instead of reference and missing the type cast. Using a malloc/new (like he said later) would allow passing in by value.
 

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
I wanted the array to be of bunch of 8-bits or 1-byte array. So, an integer would mean the output would be an array that would have 4 cells, each consisting of one-byte. I think I get what you guys are getting at though. Thanks.