c - 在 C 中以 64 位整数存储值

标签 c encoding types 64-bit

<分区>

我有一个程序

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

int main(void)
{

int i;
int x = 128;
int y = 128;
int z = 2;
int32_t coordinates = x | (y << 12) | (z << 16);

fprintf(stdout, "x = %d\n", (coordinates & 0xFF));
fprintf(stdout, "y = %d\n", ((coordinates >> 8) & 0xFF));
fprintf(stdout, "z = %d\n", ((coordinates >> 16) & 0xFF));
}

存储 x,y,z在 32 位寄存器中,但仅对 { (x,y,z)< 256} 成功.如果我希望 x,y,z 成为可能获取 2^10 (1024) 的值(所以 (x,y,z)<1024 )这怎么会发生?我知道我应该使用 64 位寄存器(?),但我仍然坚持这一点,因为轮类正在发生一些事情。

有什么想法吗?

最佳答案

  1. 不要使用signed 类型,而是使用unsigned 类型。少了很多麻烦。 @Olaf

  2. 下面的代码允许 x 在与 y 发生碰撞之前有一个 12 位的范围。它允许 y 在与 z 碰撞之前有一个 4 位 (16 - 12) 的范围。它在 16 位 int/unsigned 上有问题。

    int32_t coordinates = x | (y << 12) | (z << 16);
    

要允许 x,y,z 具有 10 位范围,请将 y 移动 10,将 z 移动 10+10。

 uint32_t coordinates = x | ((uint32_t)y << 10) | ((uint32_t)z << 20);

精确值:
(一定要使用匹配的打印说明符。)

#include <inttypes.h>
...
fprintf(stdout, "x = %" PRIu32 "\n", (coordinates & 0x3FF));
fprintf(stdout, "y = %" PRIu32 "\n", ((coordinates >> 10) & 0x3FF));
fprintf(stdout, "z = %" PRIu32 "\n", ((coordinates >> 20) & 0x3FF));

关于c - 在 C 中以 64 位整数存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776877/

相关文章:

haskell - 你会如何在 Haskell 中声明这些函数的类型?

c - 将 char 指针传递给函数的替代方法

c++ - 在整个硬盘中查找文件

.net - RichTextBox 不显示 ' 并显示一个菱形,而不是里面有一个问号

c# - .net core 2 的编码问题

python - 使用 Azure/Python 检索 unicode 数据中的表时出错

c++ - 为什么必须包含 <initializer_list> 才能使用 auto?

c++ - 在C++中传递函数类型的参数是什么意思?

c - 监听:操作不支持错误

c - 在 C 中,追加到打开的文件以供 Windows 控制台和 Linux 上的另一个程序读取