我必须在 java 中获取二进制数据并对其执行转换。例如 11110000 当我将其右移 2 时,即 11110000>>00111100
问题是,我不知道如何在 Java 中存储这样的数据,因为字节类型会将其转换为十进制格式。我需要使用位置 6 的位并将其与其他值进行异或。
我只需要知道如何实现存储二进制数据和执行所需班次的能力。
如果您使用的是整数,它将以数字格式显示,您可以使用Integer.toBinaryString(yourByte)
其次,如果您使用整数以1...
(最左边的位是 1)的格式存储二进制数,那么使用该操作>>
会将数字右移,但1
在最左边的位中输入“新”。在这种情况下你想要做的实际上是使用>>>
它来防止这种情况。
如果您使用 aint
来存储字节,并且想要开始进行所有类型的位操作,则必须使用 a 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