Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the use-cases for IsLittleEndian in BitConverter class?

I was so happy when I discovered IsLittleEndian field in BitConverter. I thought of course it should be there and I should be able to specify whatever endian I like. Well, my happiness didn’t last long. Spent some time till found out that there is no way to set the field. The field is readonly, and it is only set to true in static constructor:

static BitConverter()
{
    IsLittleEndian = true;
}

It is funny that the field is actually used in the code. For example ToInt32 method implementation looks like this:

if (IsLittleEndian)
{
     return (((numRef[0] | (numRef[1] << 8)) | (numRef[2] << 0x10)) | (numRef[3] << 0x18));
}
return ((((numRef[0] << 0x18) | (numRef[1] << 0x10)) | (numRef[2] << 8)) | numRef[3]);

So seems like the ToInt32 is perfectly capable to handle both little and big endians.

My question is: how come there is very useful piece of code that is already implemented and sitting there in the FCL, but there is no way to use it (unless you start messing with reflection of course)? Is it just because some developers didn’t meet the deadline and left the job half-done? Even if so, why the code is not available, but the field is? I hope there is a good reason for this.

I want to make myself clear. I don't need a solution on how to handle big-endian values. I do have a solution. The solution is actually shown in my question.

like image 830
Alex Aza Avatar asked Jun 20 '11 03:06

Alex Aza


1 Answers

The answer lies in looking at the reference source for the BitConverter class.

The relevant extract is:

        // This field indicates the "endianess" of the architecture.
        // The value is set to true if the architecture is
        // little endian; false if it is big endian.
#if BIGENDIAN
        public static readonly bool IsLittleEndian /* = false */;
#else
        public static readonly bool IsLittleEndian = true;
#endif

The flag is hard-wired by the preprocessor directive because the endian-ness of the architecture for which a particular version of the framework is compiled will not change.

like image 53
gmoody1979 Avatar answered Oct 10 '22 01:10

gmoody1979