`#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.
Related to CP's answer:

This numbers bits from (n-1) to 0 from the high value bits to the low, i.e. in a

`#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.
Permalink

Share this answer

Comments

steven8Gerrard
4-Jan-13 6:53am

Thank you . Much appreciated

(For instance) With a

`shift`

and a bitwise `and`

, e.g.C

// check if bit 5 is set if ( (val >> 5) & 1) { // bit is set } else { // bit unset }

Permalink

Share this answer

v2

Comments

steven8Gerrard
4-Jan-13 6:53am

Thank you . Much appreciated

CPallini
4-Jan-13 6:57am

You are welcome.

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[^]

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

Permalink

Share this answer

v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900