c# 字节顺序

c# Bits order in byte

你好,我正在尝试了解如何获取或设置位,但我被困在位顺序中。假设我有一个数字 70,即 01000110。我想将第一位更改为 true,因此它变为 11000110198。我不明白或感到困惑的地方是我找到的方法。

public static void Set(ref byte aByte, int pos, bool value)
{
    if (value)
    {
        //left-shift 1, then bitwise OR
        aByte = (byte)(aByte | (1 << pos));
    }
    else
    {
        //left-shift 1, then take complement, then bitwise AND
        aByte = (byte)(aByte & ~(1 << pos));
    }
}

public static bool Get(byte aByte, int pos)
{
    //left-shift 1, then bitwise AND, then check for non-zero
    return ((aByte & (1 << pos)) != 0);
}

在这些方法中,当我想更改第一位时,我必须传递位置 7,我猜这是最后 8 位的索引。这是为什么?为什么字节中的第一位与最后一个索引发生变化?

Why is first bit in byte changed with index of last?

基本上,通常指的是最低有效位是位 0,然后下一个是位 1 等。例如:

Bit:   76543210
Value: 01000110

所以值为 70(十进制)的字节设置了位 1、2 和 6。仅仅因为我们 写下 一个最高位在前的字节并不意味着我们将其视为 "first bit"。 (实际上,我可能会说它是 "most significant bit" 或 "high bit" 而不是使用 "first"。)

这个方案的好处是,它意味着无论值多长,您都会得到相同的值 - 位 0 总是 always "worth" 1,第 1 位 always 值 2,第 7 位 always with 128 等

现在,none 实际上会影响您的代码,它不关心我们 调用 的东西,但它关心值。幸运的是,命名约定在这里也对我们有所帮助。您只需将值 1(即 "just bit 0 set")左移 pos 位即可得到位 pos。比如要得到第5位,我们只要将1左移5位就得到100000。

如果将 1 的值看作一个完整的字节 (00000001),可能会更清楚:

00000001 << 0 = 00000001
00000001 << 1 = 00000010
00000001 << 2 = 00000100
00000001 << 3 = 00001000
00000001 << 4 = 00010000
00000001 << 5 = 00100000
00000001 << 6 = 01000000
00000001 << 7 = 10000000