Is .NET BinaryReader always little-endian, even on big-endian systems?

后端 未结 2 1637
清酒与你
清酒与你 2020-12-11 06:37

Microsoft documentation on BinaryReader for ReadUnt32 (for example) states: Reads a 4-byte unsigned integer from the current stream using little-endian encoding. However, is

2条回答
  •  佛祖请我去吃肉
    2020-12-11 07:30

    Directly from the documentation for BinaryReader.ReadUInt32:

    BinaryReader reads this data type in little-endian format.

    Note that there is no qualification about the underlying endianness of the machine. It doesn't matter if the underlying system is big endian (say XBox 360), BinaryReader will read in little endian.

    In fact, if you tear apart the source you'll see:

    public virtual long ReadInt64() {
        this.FillBuffer(4);
        uint num = (uint) (((this.m_buffer[0] |
                  (this.m_buffer[1] << 0x08)) |
                  (this.m_buffer[2] << 0x10)) |
                  (this.m_buffer[3] << 0x18));
        return num;
    }
    

    showing very clear it ignores endianness.

    Now, what will vary from little endian to big endian machines is BitConverter.ToUInt32. The output will respect the underlying endianness of the machine.

提交回复
热议问题