• C

Find Bit Within Byte

Hi,

I'm looking for a method to check if a specified bit is set within a bit.
If you have a sample of code I'll be glad to see it.

Thanks.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Hi chayahd99,

IS_SET(IN,BIT_NO)   ((IN) & (1<<(BIT_NO)))

IN is the variable/value in which you need to find the set bit
BIT_NO is the bit number you wish to check for ... 0 is for least significant bit.

Cheers!
Sunnycoder
0
Commented:
as you know

AND truth table
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1

so to find if bit number 4(right to left) is set

10010101
& 00000100
= 00000100

nonzero result means bit is 1
0
Commented:
in the above example I meant bit number 3 ;-)
0
Author Commented:
my question wasn't clear:

I want to check if a specified bit is set within a byte (not as written above).

For example:
In the first byte there are 2 bits set and I want to check if these two bits are set in the second byte. I don't mind if other bits are set in the second byte I just want to know if both bits from the first byte are set.

I'm looking for a generic method that won't require defining a mask for each of the 8 options.

Thanks.
0
Commented:
>In the first byte there are 2 bits set and I want to check if these two bits are set in the second byte. I don't mind if other bits
>are set in the second byte I just want to know if both bits from the first byte are set.

Simply AND the two bytes .. if you get non-zero then some of the bits are common ... Or do you wish to know which bits are set .. or whether all bits from byte1 are set in byte2 ... Provide some more clarifications
0
Commented:
To check if all the bits in the second byte are set in the first then compare the result of the AND opperation to the second byte.

byte1 = 00111100
byte2 = 00100100
AND      -----------
result    00100100

however:

byte1 = 11011111
byte2 = 00100100
AND      -----------
result    00000100

if ( (byte1 & byte2) == byte2) {
}

If you need to determine which bits are set you can right shift the result in a loop and AND the result with 1 (00000001) and that will tell you if the bit at position N was originally set.
0

Experts Exchange Solution brought to you by