c - 如何轻松地从 int32 中提取 2x int16?

标签 c

我有一个变量,它有 2x int16 值:

int32_t value = 0x1234ABCD; // a=0x00001234, b=0xFFFFABCD

最简单的解决方案是做一个 mask :

int32_t a = (value & 0xFFFF0000) >> 16;
int32_t b = (value & 0x0000FFFF);

但是这样,我就没有任何符号扩展,b 变成了 0x0000ABCD 而不是 0xFFFFABCD

我的下一个尝试是使用中间结构

struct dual_int16 {
   long hi:16;
   long lo:16;
}

int32_t a = (struct dual_int16)value).lo;
int32_t a = (struct dual_int16)value).hi;

不幸的是,我的编译器不允许我执行此操作“不允许使用struct Dual_int16”或“强制转换类型必须是算术或指针”。

有没有正确的方法可以在 C99 中通过符号扩展提取我的 2x int16 ?

编辑

因为我使用的是特定的编译器(ADSP-21xxx)。我没有在 stdint.h 中定义所有标准类型,例如 int16_t。我的编译器无法识别 int8_tint16_t

该架构具有混合 32-48 位双 ALU、大端字节序。

最佳答案

如果您想要有符号的 16 位值,请使用正确的类型:

#include <stdint.h>

const int32_t value = 0x1234ABCD; // a=0x00001234, b=0xFFFFABCD

const int16_t a = (value >> 16) & 0xffff;
const int16_t b = value & 0xffff;

printf("a=%hd\nb=%hd\n", (short) a, (short) b);

打印:

a=4660
b=-21555

另请注意,我在 mask 之前进行了移动,以减少 mask 的文字大小。对于现代智能优化编译器来说,这可能毫无意义,但这就是我更改它的原因。

我用过int16_t自从您使用 uint32_t并提到了 C99,这真的让我相信你应该拥有它。确保您#include <stdint.h> .

关于c - 如何轻松地从 int32 中提取 2x int16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27403632/

相关文章:

c - 使用 fgets() 扫描空白区域

c++ - C 中的副作用

java - OpenGL 灯光示例无法在 LWJGL 中使用等效代码

c - thrd_busy 和 mtx_lock()/mtx_timedlock()

仅用指针更改c中的字符串

c - 使用指针操作打印输入的字符串

c - 服务器从客户端接收到一些垃圾值?

c - 在 C 中查找文本文件的词法和行数时出错

c - OpenSSL 库 : 2 on Linux libcrypto and libssl and more than 13 on windows. 我应该在 Windows 上链接什么来编译我的示例?

c - 打开一个新的终端窗口并执行命令