计算morton代码

时间:2017-02-15 10:37:55

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

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

案例1:

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

结果将是:

11001100

案例2:

   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位。如果错误,请更正我。

1 个答案:

答案 0 :(得分:1)

我认为下面的代码可以根据您的要求工作,

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)
    }

我希望这会有所帮助。:)