public class CustomByteOrder {
// 将大字节序转为小字节序
public static byte[] getByteArray(byte[] bytes) {
int n = bytes.length;
byte[] result = new byte[n];
//使用字节移位
//处理第一个字节
for (int i = 0; i < n; i++) {
result[i] = bytes[n - i - 1];
}
return result;
}
}
class Main {
public static void main(String[] args) {
byte[] bytes = new byte[]{0x12, 0x34, 0x56, 0x78};
//假定需求为从ABCD转为DCBA
//即从 0x12 0x34 0x56 0x78 转为 0x78 0x56 0x34 0x12
// 以字节序列的方式输出
System.out.println("原字节序");
for (byte b : bytes) {
System.out.printf("%02X ", b);
}
byte[] byteArray = CustomByteOrder.getByteArray(bytes);
System.out.printf("\n转换后的字节序");
for (byte b : byteArray) {
System.out.printf("%02X ", b);
}
}
}
这里以从大端字节序转为小端字节序举例子
如果需要修改target字节序,则修改getByteArray即可