有两个变量,
uint8_t x (8 bit type)
uint16_t y (16 bit type)
,它们一起保存关于intnum的值的信息。假设num由四个字节组成abcd(其中a是最重要的)。然后x需要复制到b,y需要压缩到cd。最好的方法/代码是什么?
这对我有效:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t x = 0xF2;
uint16_t y = 0x1234;
int a = 0x87654321;
// The core operations that put x and y in a.
a = (a & 0xFF000000) | (x<<16);
a = (a & 0xFFFF0000) | y;
printf("x: %Xn", x);
printf("y: %Xn", y);
printf("a: %Xn", a);
}
这是输出:
x: F2y: 1234a: 87F21234
您可以使用并集(尽管要小心填充/对齐)
typedef union
{
uint32_t abcd;
struct
{
uint8_t a;
uint8_t b;
uint16_t cd;
} parts;
} myvaluetype;
myvaluetype myvalue = {0};
uint8_t x = 42;
uint16_t y = 2311;
myvalue.parts.b = x;
myvalue.parts.cd = y;
printf( "%un", myvalue.abcd );
Bytemasks就可以了。比如下面的
int8 x = a & 0xff;
int16 y = a & 0xff00;