How to convert 32-bit binary value to int8_t array

186 Views Asked by At

I'm trying to covert a 32 bit binary value into int8_t array. I'm not sure how to do this, and I'm struggling to find any documentation explaining the process.

I was thinking that each 8 bits represents an integer, and then that's the array, but I'm not sure.

Edit: The number I'm trying to represent is 01000011 01010000 00000000 00000000.

2

There are 2 best solutions below

5
boreddad420 On

I'm assuming that your "32 bit binary" data is a signed 32 bit integer. If that is the case, try this:

uint32_t some_number = <some 32 bit signed or unsigned int>;
int8_t data[4] = { 0 };
data[0] = (int8_t)(some_number>>24);
data[1] = (int8_t)(some_number>>16);
data[2] = (int8_t)(some_number>>8);
data[3] = (int8_t)(some_number);
0
0___________ On
int8_t *conv(uint32_t num, void *buff, int endianess)
{
    uint8_t *arr = buff;

    if(endianess)
        for(int i = 0; i < sizeof(num); i++)
        {
            arr[i] = num;
            num >>= 8;
        }
    else
        for(int i = sizeof(num) - 1; i >= 0; i--)
        {
            arr[i] = num;
            num >>= 8;
        }

    return buff;
}

https://godbolt.org/z/M7YqrW1j1