I need to convert decimal number stored in an int, to a array of bytes (aka stored in a unsigned char array).
Any clues?
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 ) );
memcpy can produce unpredictable behavior if you don't account for endianness.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).
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.
#include <limits.h> // CHAR_BIT, UCHAR_MAX
int num = 68465; // insert number here
unsigned char bytes[sizeof(int)];
for (int i=0; i<sizeof(int); i++)
{
bytes[i] = num & UCHAR_MAX;
num >>= CHAR_BIT;
}
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.