13,091,537 members (68,930 online)
Rate this:
See more:
`How to check a bit in a variable whether it is set or not using C language`
Posted 3-Jan-13 23:56pm

Rate this:

## Solution 2

`#define bit_set(val, bit_no) (((val) >> (bit_no)) & 1)`

This numbers bits from (n-1) to 0 from the high value bits to the low, i.e. in a `short` the lowest bit (value 1) is bit number 0, and the highest (value 32768) is number 15.
steven8Gerrard 4-Jan-13 6:53am

Thank you . Much appreciated
Rate this:

## Solution 1

(For instance) With a `shift` and a bitwise `and`, e.g.
```// check if bit 5 is set
if ( (val >> 5) & 1)
{
// bit is set
}
else
{
// bit unset
}```
v2
steven8Gerrard 4-Jan-13 6:53am

Thank you . Much appreciated
CPallini 4-Jan-13 6:57am

You are welcome.
Rate this:

## Solution 3

The solutions listed above are good for unstructured testing. If you are designing a system from scratch and you know that the data structure for your algorithm is going to need to check bits then you should investigate the use of bit fields.

http://en.wikipedia.org/wiki/Bit_field[^]
v2

Top Experts
Last 24hrsThis month
 ProgramFOX 220 OriginalGriff 150 Graeme_Grant 105 Richard MacCutchan 55 Dave Kreskowiak 40
 OriginalGriff 3,612 Graeme_Grant 2,019 ProgramFOX 1,927 Jochen Arndt 1,645 ppolymorphe 1,592