我有四个无符号字符,每个字符都包含一个字节,我想将它们组合在一起形成一个单独的int32_t,其中字节一个接一个地出现。
unsigned char x1 = 0b11100111;
unsigned char x2 = 0b00010101;
unsigned char x3 = 0b10000110;
unsigned char x4 = 0b00001111;
使用上面的四个字符,int32_t应该具有0b11100111000101011000011000001111
的二进制表示。
如何在c中完成?
答案 0 :(得分:3)
您可以通过一系列移位和按位OR运算来执行此操作:
uint32_t x = 0;
x |= (uint32_t)x1 << 24;
x |= (uint32_t)x2 << 16;
x |= (uint32_t)x3 << 8;
x |= (uint32_t)x4;
由于字节是无符号的,因此您应该使用uint32_t
作为目标,否则如果设置了高位,则会遇到实现定义的行为。
答案 1 :(得分:0)
你可以这样做:
#include <stdint.h>
#include <stdio.h>
int main() {
unsigned char x1 = 0b11100111;
unsigned char x2 = 0b00010101;
unsigned char x3 = 0b10000110;
unsigned char x4 = 0b00001111;
int32_t x5 = x1;
x5 <<= 8;
x5 |= x2;
x5 <<= 8;
x5 |= x3;
x5 <<= 8;
x5 |= x4;
printf("%d", x5);
}