我正在尝试交错(用于计算莫顿码)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位。如果我输入错误,请纠正我。

最佳答案

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

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

我希望这有帮助。:)

10-04 15:06