Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a specific bit from byte

Tags:

c#

I have a byte, specifically one byte from a byte array which came in via UDP sent from another device. This byte stores the on/off state of 8 relays in the device.

How do I get the value of a specific bit in said byte? Ideally an extension method would look the most elegant and returning a bool would make the most sense to me.

public static bool GetBit(this byte b, int bitNumber) {     //black magic goes here } 
like image 995
keithwarren7 Avatar asked Jan 31 '11 17:01

keithwarren7


People also ask

How do I access a specific bit?

For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.

How do you read a byte from a bit?

The first method is to use a mask to extract the value of a bit as in: msb = ( byte & 0x80 ) != 0x00; This will set the value of msb to the value of the most significant bit of byte.


1 Answers

Easy. Use a bitwise AND to compare your number with the value 2^bitNumber, which can be cheaply calculated by bit-shifting.

//your black magic var bit = (b & (1 << bitNumber-1)) != 0; 

EDIT: To add a little more detail because there are a lot of similar answers with no explanation:

A bitwise AND compares each number, bit-by-bit, using an AND join to produce a number that is the combination of bits where both the first bit and second bit in that place were set. Here's the logic matrix of AND logic in a "nibble" that shows the operation of a bitwise AND:

  0101 & 0011   ----   0001 //Only the last bit is set, because only the last bit of both summands were set 

In your case, we compare the number you passed with a number that has only the bit you want to look for set. Let's say you're looking for the fourth bit:

  11010010 & 00001000   --------   00000000 //== 0, so the bit is not set    11011010 & 00001000   --------   00001000 //!= 0, so the bit is set 

Bit-shifting, to produce the number we want to compare against, is exactly what it sounds like: take the number, represented as a set of bits, and shift those bits left or right by a certain number of places. Because these are binary numbers and so each bit is one greater power-of-two than the one to its right, bit-shifting to the left is equivalent to doubling the number once for each place that is shifted, equivalent to multiplying the number by 2^x. In your example, looking for the fourth bit, we perform:

       1 (2^0) << (4-1) ==        8 (2^3) 00000001       << (4-1) == 00001000 

Now you know how it's done, what's going on at the low level, and why it works.

like image 107
KeithS Avatar answered Sep 20 '22 19:09

KeithS