开发者

Mono Endianness

开发者 https://www.devze.com 2023-02-19 08:56 出处:网络
with .NET things are fairly simple - it is all (including ARM ASFAIK) running little endian . The question that I have is: what is happing on Mono and (potentially) big endian systems? Do the bits re

with .NET things are fairly simple - it is all (including ARM ASFAIK) running little endian .

The question that I have is: what is happing on Mono and (potentially) big endian systems? Do the bits reverse (when compared to x86)开发者_如何转开发 in Int32 / Int64 structure or does the framework force little endian rule-set?

Thanks


Your assertion that all MS .NET are little endian is not correct. It depends on the architecture that you are running on - the CLR spec says so:

From the CLI Annotated Standard (p.161) — Partition I, section 12.6.3: "Byte Ordering":

For data types larger than 1 byte, the byte ordering is dependent on the target CPU. Code that depends on byte ordering may not run on all platforms. [...]

(taken from this SO answer)

See this answer for more information on the internals of BitConverter and how it handles endianness.


A list of behavioral changes I can think of at the moment (unchecked and incomplete):

  • IPAddress.HostToNetworkOrder and IPAddress.NetworkToHostOrder
  • Nearly everything in BitConverter
  • BinaryReader and BinaryWriter (EDIT: From documentation: "BinaryReader reads this data type in little-endian format.")
  • Binary serialization
  • Everything that reads and writes Unicode in default encoding from/to streams (UnicodeEncoding) (EDIT: Default is defined as little endian)

and of course every (runtime library) function using these.

Usually Microsoft doesn't mention endianness in their docs - with some strange exceptions. For instance, BinaryReader.ReadUInt16 is defined to read little endian. Nothing mentioned for the other methods. One may assume that binary serialization is always little-endian, even on big-endian machines.

Note that XNA on XBox360 is big-endian, so this not just a theoretical problem with Mono.


c#/.Net does not make any claims on endian. int32/64 are atomic not structures.


As far as I know such conversion would happen outside the scope of your code and hidden to you. It's called "managed code" for some reasons, including such potential issues.


To know if bytes are "reversed", just check BitConverter.IsLittleEndian:

if (BitConverter.IsLittleEndian)
{
    // reverse bytes
}


Considering how similar .Net and Mono are by design, I'd say they probably handle endianness the same.

You can always test it by creating a managed int with a known value, then using reflection or marshalling to access the memory and take a look.

0

精彩评论

暂无评论...
验证码 换一张
取 消