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
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
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 ) );
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.
Or if you know what you are doing:
int n = 12345;
char* a = (char*)&n;
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).
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