将数据的每个字节按位翻转,但字节的顺序不变,例如:1000 1001 0111 0011每个字节按位翻转,变为1001 0001 1100 1110。
代码如下:
定义一个主类,进行调用:
package com.thb;
public class Demo3 {
public static void main(String[] args) {
final byte[] source = {(byte)0b10001001, 0b01110011};
final byte[] target = BitOperationUtil.invertEveryByteByBit(source);
System.out.println("input data: ");
for (int i = 0; i < target.length; i++) {
System.out.println(Integer.toBinaryString(Byte.toUnsignedInt(source[i])));
}
System.out.println("reverted data: ");
for (int i = 0; i < target.length; i++) {
System.out.println(Integer.toBinaryString(Byte.toUnsignedInt(target[i])));
}
}
}
功能实现类:
package com.thb;
public class BitOperationUtil {
private static final int ONE = 1;
/**
* 将一个字节翻转.
* 例如11001010翻转后为01010011
* @param source 输入的字节
* @return 翻转后的字节
*/
public static byte invertOneByte(byte source) {
int result = 0;
int temp;
int temp2;
int data = Byte.toUnsignedInt(source);
for (int i = 0; i <= 7; i++) {
temp = data & ONE;
// 左移位
temp2 = temp << (7 - i);
// 位或操作
result |= temp2;
// 右移1位
data >>= 1;
}
return (byte)result;
}
/**
* 将数据的每个字节按位翻转,但字节的顺序保持不变.
* 例如:1000 1001 0111 0011每个字节按位翻转,变为1001 0001 1100 1110
* @param source 输入非字符串数组
* @return 每个字节按位翻转以后的字节数组
*/
public static byte[] invertEveryByteByBit(byte[] source) {
byte[] data = source.clone();
byte tempByte;
for (int i = 0; i < data.length; i++) {
tempByte = invertOneByte(data[i]);
data[i] = tempByte;
}
return data.clone();
}
}
运行输出:
input data:
10001001
1110011
reverted data:
10010001
11001110