将三个坐标 (x,y,z) 编码为一个整数或浮点数

Encode three coordinates (x,y,z) in one integer or float number

我在 C 中得到了一个程序,它使用 MPI 来发送 processes.Because 发送的点之间的 (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 个字节编码为一个允许 4 个的 32 位整数。所以您需要的是

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 这样的东西,就像在从物理定律派生的数学表达式中看到的那样。