Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting number to byte array

Tags:

c

Hi I have a base 10 number for example 3198, and the hex representation is 0x0C7E

How do I convert that number to hex and put that hex value in a byte array in the format of [00][0C][7E], assuming the biggest hex value i can have is 0xffffff.

like image 270
kkh Avatar asked Oct 28 '25 06:10

kkh


2 Answers

Maybe this will work ?

uint32_t x = 0x0C7E;
uint8_t bytes[3];

bytes[0] = (x >> 0)  & 0xFF;
bytes[1] = (x >> 8)  & 0xFF;
bytes[2] = (x >> 16) & 0xFF;


/* Go back. */
x = (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0] << 0);
like image 127
cnicutar Avatar answered Oct 30 '25 20:10

cnicutar


Number is already a continuous memory block - no need to convert it to yet ANOTHER array ! Just fetch separate bytes by using pointer arithmetic:

EDIT: Edited to be endianness-independent

#define FAST_ABS(x) ((x ^ (x>>31)) - (x>>31))

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};

    return bint.c[0] == 1; 
}    

uint32_t num = 0xAABBCCDD;
uint32_t N = is_big_endian() * 3;

printf("first byte 0x%02X\n"
       "second byte 0x%02X\n"
       "third byte 0x%02X\n"
       "fourth byte 0x%02X\n",
       ((unsigned char *) &num)[FAST_ABS(3 - N)],
      ((unsigned char *) &num)[FAST_ABS(2 - N)],
      ((unsigned char *) &num)[FAST_ABS(1 - N)],
      ((unsigned char *) &num)[FAST_ABS(0 - N)]
       );
like image 39
Agnius Vasiliauskas Avatar answered Oct 30 '25 21:10

Agnius Vasiliauskas