简体   繁体   English

c#位字节顺序

[英]c# Bits order in byte

Hello I'm trying to understand how to get or set bit and I'm stuck in bit order. 您好,我试图了解如何获取或设置位,但我按位顺序卡住了。 Let's say I have a number 70 which is 01000110 . 假设我有一个数字70 ,即01000110 I want to change first bit to true so it becomes 11000110 which is 198 . 我想将第一位更改为true,因此它变为11000110 ,即198 What I don't understand or where I'm confused is methods I found. 我不了解或感到困惑的是找到的方法。

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);
}

In these methods when I want to change first bit I have to pass position 7 Which I guess is index of last of 8 bits. 在这些方法中,当我想更改第一位时,我必须通过位置7,我猜这是8位的最后一个索引。 Why is that? 这是为什么? Why is first bit in byte changed with index of last? 为什么字节的第一位被last索引改变?

Why is first bit in byte changed with index of last? 为什么字节的第一位被last索引改变?

Basically, bits are usually referred to such that the least-significant bit is bit 0, then the next is bit 1 etc. So for example: 基本上,通常以最低有效位是位0的方式引用位,然后是下一个是位1,等等。因此,例如:

Bit:   76543210
Value: 01000110

So a byte with value 70 (decimal) has bits 1, 2 and 6 set. 因此,值为70(十进制)的字节具有位1、2和6。 Just because we write down a byte with the most significant bit first doesn't mean that we regard that as the "first bit". 仅仅因为我们先写出最高有效位的字节并不意味着我们将其视为“第一位”。 (Indeed, I'd probably talk about it being the "most significant bit" or "high bit" instead of using "first" at all.) (实际上,我可能会说它是“最高有效位”或“高位”,而不是完全使用“第一位”。)

The good thing about this scheme is that it means you get the same value for a bit however long the value is - bit 0 is always "worth" 1, bit 1 is always worth 2, bit 7 is always with 128 etc. 这种方案的好处是,无论值长多少,您都会得到相同的值-位0 总是 “值得” 1,位1 总是值得2,位7 总是 128等。

Now, none of that actually affects your code, which doesn't care about what we call things, but it cares about values. 现在,这些都不会真正影响您的代码,这不在乎我们所谓的东西,但在乎值。 Fortunately, the naming convention helps us here, too. 幸运的是,命名约定也对我们有帮助。 You just need to shift a value of 1 (which is "just bit 0 set") left by pos bits to get bit pos . 你只需要转移值1(这是“只是位0集”)由左pos位得到位pos For example, to get bit 5, we just shift 1 left by 5 bits to get 100000. 例如,要获取第5位,我们只需将1向左移5位即可得到100000。

If you think about the value of 1 as a full byte (00000001) it may become clearer: 如果将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM