Java大小端数据互转实践
在实际项目开发中(特别是通信领域的项目开发)往往会遇到有关大小端数据转换问题——数据是以大端模式存储的,而机器是小端模式,必须进行转换,否则使用时会出问题。关于大小端模式的定义,其实就是数据的高(低)字节保存在低(高)内存地址中与否。直入主题,本文演示大小端数据转换基于Java的实现。
编码实现:
public static byte[] string2Bytes(String str) {
if (str==null || str.equals("")) {
return null;
}
str = str.toUpperCase();
int length = str.length() / 2;
char[] strChar = str.toCharArray();
byte[] bt = new byte[length];
for (int i = 0; i < length; i++) {
int index = i * 2;
bt[i] = (byte) (char2Byte(strChar[index]) << 4 | char2Byte(strChar[index + 1]));
}
return bt;
}
private static byte char2Byte(char ch) {
return (byte) "0123456789ABCDEF".indexOf(ch);
}
public final static long getLong(byte[] bt, boolean isAsc) {
//BIG_ENDIAN
if (bt == null) {
throw new IllegalArgumentException("byte array is null.");
}
if (bt.length > 8) {
throw new IllegalArgumentException("byte array size more than 8.");
}
long result = 0;
if (isAsc)
for (int i = bt.length - 1; i >= 0; i--) {
result <<= 8;
result |= (bt[i] & 0x00000000000000ff);
}
else
for (int i = 0; i < bt.length; i++) {
result <<= 8;
result |= (bt[i] & 0x00000000000000ff);
}
return result;
}
测试效果:
如上演示,我们可以成功的实现大小端数据之间的相互转换!