[Mono-dev] Are there any endian issues with unsafe code?

Brion Vibber brion at pobox.com
Mon Nov 7 21:29:30 EST 2005


Kornél Pál wrote:
> I only use Mono on little-endian systems so I have no experience in Mono on
> big-endian systems.
> 
> When I read int32 from an array of bytes using unsafe code running on Mono
> will I get the same int32 value on big-endian systems as on little-endian?

That depends on whether your read code takes endianness into account. ;)

If you do something like this, you'll get different results:

public class UnsafeTest {
	public static void Main(string[] args) {
		byte[] bits = {0x12, 0x34, 0x56, 0x78}; // ABCD
		int data;
		unsafe {
			byte *ptr = (byte *)&data;
			for (int i = 0; i < 4; i++)
				*(ptr++) = bits[i];
		}
		System.Console.WriteLine("0x{0:X}", data);
	}
}

On a big-endian PowerPC this displays: 0x12345678
On a little-endian x86, this displays: 0x78563412

I'm not sure if there's a standard way of asking the runtime for the 
processor's endianness, but it's easy enough to check by poking at a 
known int value with a byte pointer.

-- brion vibber (brion @ pobox.com)



More information about the Mono-devel-list mailing list