单个有符号字节整数位顺序似乎颠倒了

single signed byte integer bit order seems reversed

我的 C# Mono 代码(little endian OS)正在从这个在线转换器中以相反的顺序返回位,我不明白为什么:

http://www.binaryconvert.com/convert_signed_char.html

所述工具将 -45 呈现为 11010011

我的逻辑将 -45 呈现为 11001011

我可以很容易地颠倒位顺序,但我不知道我是否应该这样做,因为我不想破坏逻辑,我想了解为什么会这样。这似乎是 LSB 与 MSB 的对比,但我不明白为什么 C#(或我的 OS)选择其中之一。 little endian 与此有什么关系吗?我认为这只与字节顺序有关,与位顺序无关。还是我错了?

为什么?这是我的逻辑:

byte? sbOut = null;
sbyte sbIn = -45;

StaticHelpers.ConvertObjectTo8BitInt(
    sbIn,
    out sbOut
    );

BitArray baSignedByte = new BitArray(new byte[] { (byte)sbOut });

Console.WriteLine(
    string.Format("sbyte {0} bits {1}", sbIn, StaticHelpers.ToBitString(baSignedByte))
        );

public static class  StaticHelpers
{
    public static string ToBitString(this BitArray bits)
    {
        var sb = new StringBuilder();

        for (int i = 0; i < bits.Count; i++)
        {
            char c = bits[i] ? '1' : '0';
            sb.Append(c);
        }

        return sb.ToString();
    }

    public static void ConvertObjectTo8BitInt(
        object o,
        out byte? bOut
    )
    {
        bOut = new byte();

        if(o.GetType() == typeof(sbyte))
        {
            sbyte sbInput = (sbyte)o;

            try
            {
                bOut = unchecked((byte)sbInput);
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "Failed to cast Signed Byte to byte",
                    ex
                );
            }
        }
        else if (o.GetType() == typeof(byte))
        {
            try
            {
                bOut = (byte)o;
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "Failed to cast Byte",
                    ex
                );
            }
        }
        else
        {
            throw new Exception(
                "Failed to get sbyte or byte data type."
            );
        }
    }
}

请仔细阅读documentation

The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on. The Least Significant Bit of each byte represents the lowest index value: " bytes [0] & 1" represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4" represents bit 2, and so on.

也就是说,你的BitArray中的位顺序是从最低有效位(LSB)最高有效位(MSB) 。它与OS或其他无关。