如何使用 c 从 int32_t 中提取字节块并将其存储在 int16_t 或 int8_t 中?

How can I extract blocks of Bytes from a int32_t and store it in a int16_t or int8_t using c?

如果我有,例如:

int32_t x = 572662306;  /* 00100010001000100010001000100010 */

我想将两个最高有效字节存储在 int8_t 中:

00100010 (base 2) = 34 (base 10) 

int16_t 中的四个最高有效字节:

0010001000100010 (base 2) = 8738 (base 10) 

我该怎么做?

从中提取字节是一个非常无趣的数字。所有字节都是0x22。无论如何,这是一种方法:

#include <stdio.h>
#include <stdint.h>

int main()
{
   int32_t num = 572662306;

   int8_t num2;
   int8_t num3;

   int16_t num4;
   int16_t num5;

   printf("num in hex: 0x%x\n", num);

   num2 = (num >> 24);
   num3 = (num >> 16);
   num4 = (num >> 16);
   num5 = num;

   printf("num2 in hex: 0x%x\n", num2);
   printf("num3 in hex: 0x%x\n", num3);
   printf("num4 in hex: 0x%x\n", num4);
   printf("num5 in hex: 0x%x\n", num5);
}

输出:

num in hex: 0x22222222
num2 in hex: 0x22
num3 in hex: 0x22
num4 in hex: 0x2222
num5 in hex: 0x2222

PS

你必须小心位移负数。最好对无符号数执行位移。如果 num 为负,则向右移位的结果由实现定义。来自 C99 标准 (6.5.7/5):

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.