C# little endian or big endian?(C# 小端还是大端?)
问题描述
在允许我们通过 UDP/IP 控制它的硬件文档中,我找到了以下片段:
In the documentation of hardware that allows us to control it via UDP/IP, I found the following fragment:
在这个通信协议中,DWORD 是一个 4 字节的数据,WORD 是一个 2 字节的数据,BYTE 是单字节数据.存储格式为little endian,即4字节(32bits)数据存储为:d7-d0、d15-d8、d23-d16、d31-d24;双字节(16bits)数据存储为:d7-d0,d15-d8.
In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data, BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.
我想知道这如何转换为 C#?我必须在发送之前转换东西吗?例如,如果我想发送一个 32 位整数,还是一个 4 个字符的字符串?
I am wondering how this translates to C#? Do I have to convert stuff before sending it over? For example, if I want to send over a 32 bit integer, or a 4 character string?
推荐答案
C# 本身并没有定义字节序.但是,无论何时转换为字节,您都在做出选择.BitConverter 类有一个 IsLittleEndian 字段告诉您它的行为方式,但它没有提供选择.BinaryReader/BinaryWriter 也是如此.
C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The BitConverter class has an IsLittleEndian field to tell you how it will behave, but it doesn't give the choice. The same goes for BinaryReader/BinaryWriter.
我的 MiscUtil 库有一个 EndianBitConverter 类,它允许您定义字节序;BinaryReader/Writer 也有类似的等价物.恐怕没有在线使用指南,但它们很琐碎:)
My MiscUtil library has an EndianBitConverter class which allows you to define the endianness; there are similar equivalents for BinaryReader/Writer. No online usage guide I'm afraid, but they're trivial :)
(EndianBitConverter 还具有普通 BitConverter 中不存在的功能,即在字节数组中就地进行转换.)
(EndianBitConverter also has a piece of functionality which isn't present in the normal BitConverter, which is to do conversions in-place in a byte array.)
这篇关于C# 小端还是大端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 小端还是大端?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01