detect endianness

  • Thread starter Thread starter Jimmy Zhang
  • Start date Start date
J

Jimmy Zhang

Hi, I am wondering if C# always assumes small-endian byte order, if not,
how should I test the endianess of the platform, there doesn't seem to be a
way to check as pointers are implicit (as opposed to being explicit in C)?

Thanks
jz
 
Jimmy said:
Hi, I am wondering if C# always assumes small-endian byte order, if not,
how should I test the endianess of the platform, there doesn't seem to be a
way to check as pointers are implicit (as opposed to being explicit in C)?

Thanks
jz

Just read the first byte of a short or int with the value 1. If the byte
is 1, the memory model is little-endian.

My recollection of pointer syntax is a bit muddy, but something like
this would do it:

byte b;
unsafe {
int i = 1;
byte* bp = (byte*)&i;
b = *bp;
}
 
Jimmy said:
Hi, I am wondering if C# always assumes small-endian byte order, if not,
how should I test the endianess of the platform, there doesn't seem to be a
way to check as pointers are implicit (as opposed to being explicit in C)?

MS .NET only runs on little endian platforms

Mono runs on both little and big endian platforms.

For obvious performance reasons it uses the native
endianess internally, but that is completely transparent.

It is only relevant when you are exchanging data.

System.IO BinaryReader and BinaryWriter always
uses little endian.

System BitConverter uses actual system endianess.

BitConverter also has a static field IsLittleEndian
you can use to test for.

Arne
 
Arne Vajhøj said:
MS .NET only runs on little endian platforms

Mono runs on both little and big endian platforms.

For obvious performance reasons it uses the native
endianess internally, but that is completely transparent.

It is only relevant when you are exchanging data.

System.IO BinaryReader and BinaryWriter always
uses little endian.

System BitConverter uses actual system endianess.

BitConverter also has a static field IsLittleEndian
you can use to test for.

And in addition, if you want complete control, you can use my
EndianBitConvert and EndianBinaryReader/Writer classes:

http://www.pobox.com/~skeet/csharp/miscutil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top