开发者

Is C# Endian sensitive?

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

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

always a开发者_运维百科ssign 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?


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.


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".


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜