c# - 将小端转换为 int

标签 c#

首先,我认为这个问题与 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/

相关文章:

c# - 如何正确排序 DataTable 的字符串数字列

c# - LINQ 生成的 IEnumerable 和原始列表之间有什么关系?

c# - 不能在 DropDownList 中选择多个项目

c# - 具有图像标题和描述的自定义水平滚动内容 slider

c# - 如何在右键单击时获取数据网格列索引? MVVM WPF

javascript - jQuery 在按钮单击时获取最接近的表单

c# - SonarQube Scanner 执行期间出错 : java. lang.IllegalArgumentException: 79 不是指针的有效行偏移

c# - 读取标准输出问题

c# - 可以从主应用程序启动的带有 WinForms 的 DLL

c# - C# 中的 IPv6 地址范围