C#代码里就是小端序,Java代码里就是大端序,
大端位:big endian,是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,也叫高尾端
小端位:little endian,是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中,也叫低尾端
这个最早是指一个鸡蛋的大头和小头,分别被称为大端和小端,出自格列佛游记,两个国家因为吃鸡蛋从大头开始还是小头开始发生了战争。这是翻译的问题,大小端位是直译,高低尾端是意译,显然意译的更好理解一点。
具体是什么意思呢,看一个具体的例子,假如"11223344"存储在内存中,
地址有顺序,高尾端,就是按照地址的顺序,尾端的位置放高字节的数据,低尾端就是地址的尾端放低字节的数据。就是两种存储方式,各有利弊,具体我就不赘述了,主要是在用的时候,需要注意,
我在C#代码里使用
BitConverter.ToInt64(buff, index);
BitConverter.ToInt16(bufftemp, 0);
BitConverter.ToDouble(buff, index);
BitConverter.ToSingle(rSRPBytes, 0);
来解析数据,然后换到Java里就不行,最后检查一下,才发现,C#使用的是小端序,Java使用的是大端序,然后手动调整了一下,就成功了,分享几个我写的工具方法,供大家参考:
public double arr2Double(long[] arr,int index){
long[] subArr = new long[8];
System.arraycopy(arr, index, subArr, 0, 8);
String binaryString = "";
for(int i = 7;i > -1;i--){
String binary = Long.toBinaryString(subArr[i]);
while(binary.length() < 8){
binary = "0" + binary;
}
binaryString = binaryString + binary;
}
long bits = Long.parseUnsignedLong(binaryString, 2);
double result = Double.longBitsToDouble(bits);
return result;
}
public long arr2Long(long[] arr,int index){
long[] subArr = new long[8];
System.arraycopy(arr, index, subArr, 0, 8);
String binaryString = "";
for(int i = 7;i > -1;i--){
String binary = Long.toBinaryString(subArr[i]);
while(binary.length() < 8){
binary = "0" + binary;
}
binaryString = binaryString + binary;
}
long result = Long.parseUnsignedLong(binaryString, 2);
return result;
}
public short arr2Short(long[] arr,int index){
long[] subArr = new long[2];
System.arraycopy(arr, index, subArr, 0, 2);
String binaryString = "";
for(int i = 1;i > -1;i--){
String binary = Long.toBinaryString(subArr[i]);
while(binary.length() < 8){
binary = "0" + binary;
}
binaryString = binaryString + binary;
}
short result = Short.parseShort(binaryString, 2);
return result;
}
public int arr2Int(long[] arr,int index){
long[] subArr = new long[4];
System.arraycopy(arr, index, subArr, 0, 4);
String binaryString = "";
for(int i = 3;i > -1;i--){
String binary = Long.toBinaryString(subArr[i]);
while(binary.length() < 8){
binary = "0" + binary;
}
binaryString = binaryString + binary;
}
int result = Integer.parseUnsignedInt(binaryString, 2);
return result;
}
public float arr2Float(long[] arr,int index){
long[] subArr = new long[4];
System.arraycopy(arr, index, subArr, 0, 4);
String binaryString = "";
for(int i = 3;i > -1;i--){
String binary = Long.toBinaryString(subArr[i]);
while(binary.length() < 8){
binary = "0" + binary;
}
binaryString = binaryString + binary;
}
int bits = Integer.parseUnsignedInt(binaryString, 2);
float result = Float.intBitsToFloat(bits);
return result;
}