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

C Programming Tutorial - Low Level Operations

By David Bolton, About.com

5 of 10

Another Example that Demonstrates all three Binary Operations

Example 2, listed below uses this PrintBinary() function to demonstrate the three binary operations.

Download Example 2

int a =0x45;
int b= 0x67;
int c;
printf("This is a & b\n") ;
printf("a ") ;PrintBinary(a,8) ;
printf("b ") ;PrintBinary(b,8) ;
c= a & b;
printf(" ---------\n") ;
printf("a&b ") ;PrintBinary(c,8) ;
printf("\nThis is a | b\n") ;
printf("a ") ;PrintBinary(a,8) ;
printf("b ") ;PrintBinary(b,8) ;
c= a | b;
printf(" ---------\n") ;
printf("a|b ") ;PrintBinary(c,8) ;
printf("\nThis is a ^ b\n") ;
printf("a ") ;PrintBinary(a,8) ;
printf("b ") ;PrintBinary(b,8) ;
c= a ^ b;
printf(" ---------\n") ;
printf("a^b ") ;PrintBinary(c,8) ;
Just as >> shifts bits to the right then << shifts them to the left and is the same as multiplying by 2 for each position you shift them left.

X << n is the same as X* 2n. 5 << 4 is 80. So is 5 *24

Flipping Bits

Another bit operator, most commonly seen in if statements is ~, known as the not operator, it flips every bit. It's the same as xor with -1 but not quite as intuitive. These two statements do exactly the same.
c =~c;
c^=-1;
Some caution should be exercised with using ~ on signed numbers or characters. Unsigned numbers, those that start at 0 are fine but if applied to a negative number, it will become positive and vice versa. The CPU doesn't care whether the contents of a memory location hold a character, a signed number (or unsigned) or even a pointer. It will happily let you flip bits, regardless of whether it is a meaningful operation. So what exactly does ~'A' mean? When assigned to an int, C happily compiles it and outputs -66.

On the next page About Hexadecimal and Binary

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Another Example that Demonstrates all three Binary Operations

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

All rights reserved.