【问题标题】: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 中提取字节块并使用 c 将其存储在 int16_t 或 int8_t 中?
【发布时间】:2015-05-25 23:57:50
【问题描述】:

如果我有,例如:

int32_t x = 572662306;  /* 00100010001000100010001000100010 */

我想将两个最重要的字节存储在int8_t 中:

00100010 (base 2) = 34 (base 10) 

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

0010001000100010 (base 2) = 8738 (base 10) 

我该怎么做?

【问题讨论】:

  • 你试过什么?你知道按位和移位运算符吗?标准 C 也不支持 4 位字节。你的意思是轻咬?

标签: c binary byte converter stdint


【解决方案1】:

从中提取字节是一个非常无趣的数字。所有字节都是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);
}

输出:

十六进制数:0x22222222 十六进制的 num2:0x22 十六进制的 num3:0x22 十六进制的 num4:0x2222 十六进制的 num5:0x2222

附言

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

E1 &gt;&gt; E2 的结果是E1 右移了E2 位位置。如果E1 具有无符号类型或E1 具有有符号类型和非负值,则结果的值是E1 /2E2 商的整数部分。 如果E1 具有带符号类型和负值,则结果值是实现定义的。

【讨论】:

  • 有点迂腐:你应该使用无符号类型,否则如果设置了一个 MSB,你会得到意外的输出:ideone.com/eQ8fsL
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2019-12-05
  • 2014-12-24
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2015-03-19
相关资源
最近更新 更多