【问题标题】:Calculating morton code计算莫顿代码
【发布时间】:2017-07-03 23:18:44
【问题描述】:

我正在尝试交错(用于计算 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 位。如果我错了,请纠正我。

【问题讨论】:

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


    【解决方案1】:

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

    莫顿码是 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)
        }
    

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

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2016-02-12
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2019-11-11
      相关资源
      最近更新 更多