Link to home
Start Free TrialLog in
Avatar of chayahd99
chayahd99

asked on

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.
Avatar of sunnycoder
sunnycoder
Flag of India image

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
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
in the above example I meant bit number 3 ;-)
Avatar of chayahd99
chayahd99

ASKER

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.
>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
ASKER CERTIFIED SOLUTION
Avatar of GnarOlak
GnarOlak

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I agree with sunnycoder in his both posts. He is right either with testing single bit (as macro) or with ANDing operands.