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

Solved

Posted on 2006-04-23

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.

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.

7 Comments

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

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

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.

>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

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.

By clicking you are agreeing to Experts Exchange's Terms of Use.

Title | # Comments | Views | Activity |
---|---|---|---|

Change to the struct | 72 | 188 | |

Problem to show menu | 5 | 70 | |

An API detour question | 7 | 35 | |

xamarin c# deserialize Json containing nested object | 2 | 26 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**23** Experts available now in Live!