tags:

views:

157

answers:

5

Hi all,

I need to convert decimal number stored in an int, to a array of bytes (aka stored in a unsigned char array).

Any clues?

Thanx

+1  A: 

Simplest possible approach - use sprintf (or snprintf, if you have it):

unsigned char a[SOMESIZE]
int n = 1234;
sprintf( a, "%d", n );

Or if you want it stored in binary:

unsigned char a[sizeof( int ) ];
int n = 1234;
memcpy( a, & n, sizeof( int ) );
anon
Warning: `memcpy` can produce unpredictable behavior if you don't account for endianness.
Zarel
@Zarel The results will be entirely predictable, but perhaps unwanted.
anon
"Unpredictable" in the sense that you won't be able to predict the results unless you know the endianness of the processor you run it on.
Zarel
@Zarel: if you care about endianness just call hton() on your int before memcpy() and you get a fixed order (network order).
kriss
ShinTakezou
A: 

Warning: untested code.

This should be an endianness-agnostic conversion. It goes from low to high. There's probably a more efficient way to do it, but I can't think of it at the moment.

int num = 68465; // insert number here
unsigned char bytes[sizeof(int)/8];
for (int i=0; i<sizeof(int)/8; i++)
{
    bytes[i] = num & 0xFF;
    num >>= 8;
}

I'm posting this mostly because I don't see another solution here for which the results don't change depending on what endianness your processor is.

Zarel
But perhaps the user wants them to change - to maintain the same byte order as in the original int. Also, your array sizing and loop control calculation is wrong.
anon
+1  A: 

Or if you know what you are doing:

int n = 12345;
char* a = (char*)&n;
leppie
A: 

I understand the problem as converting a number to a string representation (as Neil does).

Below is a simple way to do it without using any lib.

int i = 0;
int j = 0;
do {a[i++] = '0'+n%10; n/=10;} while (n);
a[i--] = 0;
for (j<i; j++,i--) {int tmp = a[i]; a[i] = a[j]; a[j] = tmp;}

The question probably needs some clarification as others obviously understood you wanted the underlying bytes used in internal representation of int (but if you want to do that kind of thing, you'd better use some fixed size type defined in instead of an int, or you won't know for sure the length of your byte array).

kriss
A: 

This could work

int n=1234;    
const int arrayLength=sizeof(int);
unsigned char *bytePtr=(unsigned char*)&n;

for(int i=0;i<arrayLength;i++)
{
   printf("[%X]",bytePtr[i]);
}

Take care of order that depends on endianness

Hernán Eche
Thanks; I used this :)
Emi