• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

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.
0
chayahd99
Asked:
chayahd99
1 Solution
 
sunnycoderCommented:
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
 
hoomanvCommented:
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
 
hoomanvCommented:
in the above example I meant bit number 3 ;-)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
chayahd99Author 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
 
sunnycoderCommented:
>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
 
GnarOlakCommented:
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) {
   /* your code here */
}

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
 
NopiusCommented:
I agree with sunnycoder in his both posts. He is right either with testing single bit (as macro) or with ANDing operands.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now