C语言 如何将32位二进制值转换为int8_t数组

icomxhvb  于 2023-04-19  发布在  其他
关注(0)|答案(2)|浏览(241)

我正在尝试将一个32位的二进制值转换为int8_t数组。我不知道如何做到这一点,我很难找到任何解释这个过程的文档。
我在想,每8位代表一个整数,然后这就是数组,但我不确定。
编辑:我试图表示的数字是01000011 01010000 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

k7fdbhmy

k7fdbhmy1#

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

biswetbf

biswetbf2#

我假设你的“32位二进制”数据是一个有符号的32位整数。如果是这样的话,试试这个:

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

相关问题