gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:58 25 4
gpt4 key购买 nike

如果我有,例如:

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: 0x22222222num2 in hex: 0x22num3 in hex: 0x22num4 in hex: 0x2222num5 in hex: 0x2222

附言

您必须小心位移负数。最好对无符号数执行位移。如果 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.

关于c - 如何从 int32_t 中提取字节 block 并使用 c 将其存储在 int16_t 或 int8_t 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com