1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Low Level Operations

By David Bolton, About.com

2 of 10

Manipulating Individual Bits with Binary Operations

If byte b is "binary anded" with a byte m where all the bits of m are 0 except for the bit in b that we are interested in, then we can isolate that bit. If the value of the expression is non zero then that bit is set, if it zero it isn't.

So

if (a & b)
    printf("a & b was non zero") ;
else
    printf("a & b was zero") ;

Beware - Trap Ahead!

You might think from this that there seems little difference between (a && b) and (a & b). Sometimes this is true, but not always. E.g. if a is 4 and b is 2, then (a && b) is true as both are non zero but (a & b) is false!
a     000001002
b     000000102
-------------------
a & b 000000002

Setting Bits

Use the "binary or" operation for this which sets any bits to 1 in the result if either (or both) of the two numbers has a 1 in its corresponding bits.
a     100101102
b     011111002
--------------------
a | b 111111102
So to set the bit in a (below) at position 2 to a 1 we or with b = 00000100
a    100100102
b     000001002
--------------------
a | b 100101102

Toggle that bit!

The 3rd binary operation is "exclusive or" or xor which in C uses the ^ operator. If two numbers a and b are xored together then each bit in the result is 0 If the corresponding bits are identical, 1 if they are different. If it helps, think of xor as a "Not the same" function.

To toggle any bit, simply "binary xor" the number with a 1 set in the appropriate bit position. If the corresponding bit is 1, the result bit is 0 etc.

a    100100102
b    000001002
--------------------
a ^ b 100101102

On the next page - An example of printing binary numbers.

2 of 10

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Manipulating Individual Bits with Binary Operations

©2008 About.com, a part of The New York Times Company.

All rights reserved.