c++ - 计算莫顿码

标签 c++ math bit-manipulation 64-bit z-order-curve

我正在尝试交错(用于计算莫顿代码)2 个带符号的长数字表示 xy(32 位)的值

案例 1:

x = 10;  //1010
y = 10;  //1010

结果将是:

11001100

案例二:

   x = -10;
   y = 10;

二进制表示是,

x = 1111111111111111111111111111111111111111111111111111111111110110
y = 1010

对于交错,我只考虑 32 位表示,其中我可以将 x 的第 31 位与 y 的第 31 位交错, 使用以下代码,

signed long long x_y;
for (int i = 31; i >= 0; i--)
        {

                    unsigned long long xbit = ((unsigned long) x)& (1 << i);
                    x_y|= (xbit << i);

                    unsigned long long ybit = ((unsigned long) y)& (1 << i);

                    if (i != 0)
                    {
                                x_y|= (x_y<< (i - 1));
                    }
                    else
                    {
                                (x_y= x_y<< 1) |= ybit;
                    }
        }

上面的代码工作正常,如果我们有 x 积极和 y 消极但案例 2 失败了,请帮助我,哪里出了问题? 负数使用 64 位,而正数使用 32 位。如果我错了,请纠正我。

最佳答案

我认为下面的代码可以满足您的要求,

Morton 码是 64 位的,我们通过交错从两个 32 位的数字中生成 64 位的数字。 由于数字是有符号的,我们必须将负数视为,

if (x < 0) //value will be represented as 2's compliment,hence uses all 64 bits
    {
        value = x; //value is of 32 bit,so use only first lower 32 bits 
        cout << value;
        value &= ~(1 << 31); //make sign bit to 0,as it does not contribute to real value.
    }

类似地为 y 做。

以下代码进行交织,

unsigned long long x_y_copy = 0; //make a copy of ur morton code
//looping for each bit of two 32 bit numbers starting from MSB.
    for (int i = 31; i >=0; i--)
    {
        //making mort to 0,so because shifting causes loss of data
        mort = 0;
        //take 32 bit from x
        int xbit = ((unsigned long)x)& (1 << i);
        mort = (mort |= xbit)<<i+1;    /*shifting*/
        //copy  formed code to copy ,so that next time the value is preserved for appending
        x_y_copy|= mort;
         mort =0;
        //take 32nd bit from 'y' also
        int ybit = ((unsigned long)y)& (1 << i);
        mort = (mort |= ybit)<<i;
        x_y_copy |= mort;
    }
    //this is important,when 'y'  is negative because the 32nd bit of 'y' is set to 0 by above first code,and while moving 32 bit of 'y' to morton code,the value 0 is copied to 63rd bit,which has to be made to 1,as sign bit is not 63rd bit.
    if (mapu_y < 0)
    {
        x_y_copy = (x_y_copy) | (4611686018427387904);//4611686018427387904 = pow(2,63)
    }

希望对您有所帮助。:)

关于c++ - 计算莫顿码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246964/

相关文章:

c++ - 是否可以使用 static_cast 避免 vtable 开销?

C++ 迭代器 - 推导维度

c++ - Eclipse PTP 挂起 OpenMPI 应用程序的启动调试 session

math - 如何通过指定alpha混合量来计算RGB颜色?

php - 如何在PHP中将数字除以没有余数?

wpf - 如何计算沿曲线的点?

python - 覆盖特定范围内某些位的最佳方法

php - 如何替换内部 PHP 方法?

java - 在java中解码一个字节

c - 用于设置和清除位的宏