Is C# Endian sensitive?

穿精又带淫゛_ 提交于 2019-12-10 12:33:39

问题


Is C# ever Endian sensitive, for example, will code such as this:

int a = 1234567;
short b = *(short*)&i;

always assign the same value to b. If so, what value will it be?

If not, what good ways are there to deal with endianness if code with pointers in?


回答1:


C# doesn't define the endianness. In reality, yes it will probably always be little-endian (IIRC even on IA64, but I haven't checked), but you should ideally check BitConverter.IsLittleEndian if endianness is important - or just use bit-shifting etc rather than direct memory access.

To quote a few lines from protobuf-net (a build not yet committed):

WriteInt64(*(long*)&value);
if (!BitConverter.IsLittleEndian)
{   // not fully tested, but this *should* work
    Reverse(ioBuffer, ioIndex - 8, 8);
}

i.e. it checks the endianness and does a flip if necessary.




回答2:


Yes, I believe that code is endian-sensitive. The value of b will be the least-significant bytes on a little-endian processor, and the most-significant bytes on a big-endian processor. To make this simpler to see, let's switch to hex:

using System;

class Test
{
    unsafe static void Main()
    {
        int a = 0x12345678;
        short b = *(short*)&a;
        Console.WriteLine(b.ToString("x"));
    }
}

On my x86 box, that prints "5678" showing that the least-significant bytes were at the "start" of the vaue of a. If you run the same code on a processor running in big-endian mode (probably under Mono) I'd expect it to print "1234".




回答3:


As far as I can tell, neither the C# nor the Common Language Infrastructure specifications have endianness requirements for pointer-based bitwise and mathematical operations. The CLI does state that binary data stored in a MSIL executable file must be in little endian format. And the general drift of the documents would indicate that code shouldn't be dependent on any specific memory representation (including packed or unpacked arrays, etc.) except under special circumstances.




回答4:


You really shouldn't be doing pointer swizzling in C#. You should try compiling your code before asking what it will do.



来源:https://stackoverflow.com/questions/2247907/is-c-sharp-endian-sensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!