Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C C#
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: bad
good
Please Sign up or sign in to vote.

Solution 2

Related to CP's answer:
 
#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  
Comments
steven8Gerrard at 4-Jan-13 6:53am
   
Thank you . Much appreciated
Rate this: bad
good
Please Sign up or sign in to vote.

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
}
  Permalink  
v2
Comments
steven8Gerrard at 4-Jan-13 6:53am
   
Thank you . Much appreciated
CPallini at 4-Jan-13 6:57am
   
You are welcome.
Rate this: bad
good
Please Sign up or sign in to vote.

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

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 510
1 CPallini 330
2 OriginalGriff 215
3 George Jonsson 120
4 ChauhanAjay 104
0 OriginalGriff 6,464
1 Sergey Alexandrovich Kryukov 5,915
2 CPallini 5,175
3 George Jonsson 3,559
4 Gihan Liyanage 2,522


Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 4 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100