-2

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.

  • 1
    Look into using a `union`. – Fe2O3 Apr 13 '23 at 23:15
  • What do you mean by a "binary value"? All numbers are stored, in the end, in binary, in a computer. Is this a string of `0` and `1`? Your question is very unclear. Do you have some code to share for your attempt? – pmacfarlane Apr 13 '23 at 23:21
  • Usually when disassembling an object into the bytes that represent it, unsigned types (`unsigned char` or `uint8_t`) are used, not a signed type, due to issues with sign bits and incomplete specifications of the behavior of signed types in the C standard. Are you sure you want `int8_t`, not `uint8_t`? – Eric Postpischil Apr 13 '23 at 23:50

2 Answers2

0

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);
boreddad420
  • 187
  • 1
  • 7
0
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

0___________
  • 60,014
  • 4
  • 34
  • 74