使用java执行二进制移位

时间:2013-09-15 03:43:40

标签: java binary xor shift

我必须在java中获取二进制数据并对其执行转换。 对于例如11110000当我右移2时,即11110000>> 00111100

问题在于,我不知道如何在Java中存储这样的数据,因为字节类型将其转换为十进制格式。我需要使用位置6处的位并将其与其他值进行异或。

我只需要知道如何实现存储二进制数据和执行所需班次的能力。

1 个答案:

答案 0 :(得分:4)

如果您使用的是整数,它会以数字格式显示,您可以使用Integer.toBinaryString(yourByte)

解决它

其次,如果您使用整数来存储格式为1...的二进制数(最左边的位为1),那么使用操作>>会将数字向右移动但输入“新”1进入最左边的位。在这种情况下你想要做的事实上是使用>>>来防止这种情况。

如果你使用int来存储你的字节,并且你想要开始进行所有类型的操作,那么你必须使用mask,例如,在第3和第5位:

    int number = 7; //just an example, here binary rep: 00111 => requested output will be 10011
    System.out.println("number = " + Integer.toBinaryString(number));
    int mask3Bit = 4;//binary rep: 0100
    System.out.println("mask3Bit = " + Integer.toBinaryString(mask3Bit));

    int mask5Bit = 16; //binary rep: 10000
    System.out.println("mask5Bit = " + Integer.toBinaryString(mask5Bit));

    // now we'll create a mask that has all the bits on except the 3rd and 5th bit:
    int oppositeMask = -1;
    oppositeMask ^= mask3Bit;
    oppositeMask ^= mask5Bit;
    System.out.println("oppositeMask = " + Integer.toBinaryString(oppositeMask));

    //check if the 3rd bit is on:
    mask3Bit = number & mask3Bit;
    //shift twice to the right
    mask3Bit <<= 2;
    System.out.println("mask3Bit = " + Integer.toBinaryString(mask3Bit));
    //now do the same with the 5th bit
    //check if the 5th bit is on:
    mask5Bit = number & mask5Bit;
    //shift twice to the right
    mask5Bit >>= 2;
    System.out.println("mask5Bit = " + Integer.toBinaryString(mask5Bit));

    //now we'll turn off the 3rd and 5th bits in the original number
    number &= oppositeMask;
    System.out.println("number = " + Integer.toBinaryString(number));
    //and use the masks to switch the bits
    number |= mask3Bit;
    number |= mask5Bit;
    //let's check it out now:
    System.out.println("new number = " + Integer.toBinaryString(number));

输出:

number = 111
mask3Bit = 100
mask5Bit = 10000
oppositeMask = 11111111111111111111111111101011
mask3Bit = 10000
mask5Bit = 0 //here it's zero cause the original number has zero in the 5th bit and we used &. If the bit was on we would have gotten '100'
number = 11
new number = 10011