-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.

3
  • 1
    Look into using a union. Commented Apr 13, 2023 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? Commented Apr 13, 2023 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? Commented Apr 13, 2023 at 23:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);

5 Comments

Why not just use memcpy()?
valid point, memcpy would likely be more efficient in terms of compiler output, but for simplicity and educational sake, I just assigned them straight up like that that @JohnScott
@JohnScott, memcpy, byte order would vary by system.
No need to make data 5 bytes long. This isn't a string.
what about endianess

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.