解决大端小端问题
1,什么是大端小端
下面是经过简化的BitConverter.ToInt16源码,其中的IsLittleEndian代表这台计算机是大端编码还是小端编码,不同的计算机编码方式会有不同。
不同的计算机编码方式不同,读取出来的数据长度有可能不同
public static short ToInt16(byte[] value, int startIndex) {
if( startIndex % 2 == 0) { // data is aligned
return *((short *) pbyte);
}
else {
if( IsLittleEndian) {
return (short)((*pbyte) | (*(pbyte + 1) << 8)) ;
}
else {
return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
16进制代表258,大端和小端存储方式不同,如下图可见:
大端模式:
小端模式: