首先,我认为这个问题与 C# 无关。但也可以用于其他语言,例如 C。
我现在正在尝试解析一种以 4 字节小端格式存储整数的文件格式。 TBH,我不知道小端格式和大端格式是如何工作的。
但我需要将它们转换成可用的 int 变量。
例如, 02 00 00 00 = 2
到目前为止,我有这段代码来转换前 2 个字节:(我使用 FileStream.Read 将原始数据存储到缓冲区变量中)
int num = ((buffer[5] << 8) + buffer[4]);
但它只会转换前两个字节。 (示例中的 02 00,不是 02 00 00 00)
任何形式的帮助将不胜感激:)
最佳答案
int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) {
return (data[startIndex] << 24)
| (data[startIndex + 1] << 16)
| (data[startIndex + 2] << 8)
| data[startIndex + 3];
}
int GetLittleEndianIntegerFromByteArray(byte[] data, int startIndex) {
return (data[startIndex + 3] << 24)
| (data[startIndex + 2] << 16)
| (data[startIndex + 1] << 8)
| data[startIndex];
}
关于c# - 将小端转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1674160/