gpt4 book ai didi

c - 将三个坐标 (x,y,z) 编码为一个整数或 float

转载 作者:行者123 更新时间:2023-11-30 19:38:15 24 4
gpt4 key购买 nike

我有一个 C 程序,它使用 MPI 来在进程之间发送 (x,y,z) 轴上特定点的坐标。因为发送的点是连续类型(二维数组的行) )我想对存储在结构中的坐标进行编码

  Struct pnts{

int x;
int y;
int z;
}pnt;

在一个数字(INTEGER/FLOAT)中,我需要对这三个坐标进行编码坐标是区间 [0, 28] 内的整数例如:x = 16、y = 2、z = 4 相对于 x < y <z

有什么想法吗?

最佳答案

这是一件非常简单的事情,您需要将 3 个字节编码为 32 位整数,该整数允许 4 个字节。所以您需要的是

int32_t coordinates;

coordinates = x | (y << 8) | (z << 16);

然后您可以使用位标志掩码访问坐标。

测试程序:

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

int
main(void)
{
int x = 16;
int y = 2;
int z = 4;
int32_t coordinates = x | (y << 8) | (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));
return 0;
}

但是你不能编码 256,因为它需要多一位,记住你从 20 开始,所以你只能用 8 位表示 255,所以这里有一个想法

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

#define XSHIFT 0
#define YSHIFT 9
#define ZSHIFT 18

#define GET_X(x) (((x) >> XSHIFT) & 0x1FF)
#define GET_Y(y) (((y) >> YSHIFT) & 0x1FF)
#define GET_Z(z) (((z) >> ZSHIFT) & 0x1FF)
#define ENCODE(x, y, z) (((x) << XSHIFT) | ((y) << YSHIFT) | ((z) << ZSHIFT))

int
main(void)
{
int32_t coordinates = ENCODE(256, 0, 1);

fprintf(stdout, "x = %d\n", GET_X(coordinates));
fprintf(stdout, "y = %d\n", GET_Y(coordinates));
fprintf(stdout, "z = %d\n", GET_Z(coordinates));
return 0;
}

使用 32 位整数中剩余 8 位中的一位额外位。

注意:也许您(和其他人)认为定义 XSHIFT 是多余的,但我认为这些表达式更有意义并且是更容易阅读。我相信这是我从研究物理学中学到的东西,我很难在代码中看到像 x + 7 这样的东西,因为它是在从物理定律导出的数学表达式中。

关于c - 将三个坐标 (x,y,z) 编码为一个整数或 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38482698/

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