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. I want to change first bit to true so it becomes 11000110 which is 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. Why is that? Why is first bit in byte changed with index of last?
Why is first bit in byte changed with index of 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:
Bit: 76543210
Value: 01000110
So a byte with value 70 (decimal) has bits 1, 2 and 6 set. 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.
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
. For example, to get bit 5, we just shift 1 left by 5 bits to get 100000.
If you think about the value of 1 as a full byte (00000001) it may become clearer:
00000001 << 0 = 00000001
00000001 << 1 = 00000010
00000001 << 2 = 00000100
00000001 << 3 = 00001000
00000001 << 4 = 00010000
00000001 << 5 = 00100000
00000001 << 6 = 01000000
00000001 << 7 = 10000000
See more on this question at Stackoverflow