convert unsigned integer to byte array in C

15,533

Solution 1

It's more difficult if you have to convert it to an array, but if you just want to access the individual bytes, then you can do

char* bytes = (char*)&unint;

If you really do want to make an array (and therefore make a copy of the last 3 bytes, not leave them in place) you do

unsigned char bytes[3]; // or char, but unsigned char is better

bytes[0] = unint >> 16 & 0xFF;
bytes[1] = unint >> 8  & 0xFF;
bytes[2] = unint       & 0xFF;

Solution 2

You can do using it the bitwise right shift operator:

array[0] = unint;
array[1] = unint >> 8;
array[2] = unint >> 16;

The least signifcant byte of uint is stored in the first element of the array.

Share:
15,533
Thi
Author by

Thi

Just a Developer :D

Updated on June 30, 2022

Comments

  • Thi
    Thi almost 2 years

    Can you explain about how to convert the last 3 bytes of data from unsigned integer to a character array?

    Example:

    unsigned int unint = some value;
    unsigned char array[3];