将值存储在C中的64位整数中

时间:2016-08-04 20:28:16

标签: 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位寄存器(?)但是我坚持这个,因为有些事情正在发生变化。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

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

  2. 以下代码允许Bc.data在与x发生冲突之前具有12位范围。它允许y在与y发生碰撞之前具有4位(16 - 12)范围。它有16位z的麻烦。

    int/unsigned
  3. 要允许int32_t coordinates = x | (y << 12) | (z << 16); 拥有10位范围,请将x,y,z移动10,将y移动10 + 10.

    z

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

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

答案 1 :(得分:1)

如果你有3个10位字段,那么它们将适合32位int。你可以这样做:

int32_t coordinates = (int32_t)(x & 0x3ff) | 
                      ((int32_t)(y & 0x3ff) << 10) | 
                      ((int32_t(z & 0x3ff) << 20);

首先对每个数字执行0x3ff的按位AND,以确保只获得最低的10位。然后将结果转换为结果的类型,以确保当值移位时,对于中间值,它不会移动太远。然后,每个值通过移位放置在10位偏移处。

然后你可以按如下方式阅读它们:

fprintf(stdout, "x = %d\n", (coordinates & 0x3FF));
fprintf(stdout, "y = %d\n", ((coordinates >> 10) & 0x3FF));
fprintf(stdout, "z = %d\n", ((coordinates >> 20) & 0x3FF));
相关问题