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

C Programming Tutorial - Low Level Operations

By , About.com Guide

3 of 10

Example 1 - Using a Binary And to Extract Bits

Example 1

This example prints out ints in binary.

Download Example 1

// ex1.c
//
#include <stdio.h>

void PrintBinary(int x,int d)
{
    char buffer[33];
    int index;
    index=0;
    while (d >0) {
        if (x & 1)
            buffer[index++]='1';
        else
            buffer[index++]='0';
        x >>= 1;
        d--;
    }
  while (index >0 )
    printf("%c",buffer[--index]) ;

  printf("B\n") ;
  return;
}

int main(int argc, char* argv[])
{
    PrintBinary(10,6) ;
    PrintBinary(8,4) ;
    PrintBinary(32765,16) ;
    return 0;
}
This processes an int from right to left. It uses a "binary and" to get the rightmost bit, putting '1' for non zero and '0' in a buffer. This continues for as many digits as were specified in the second parameter to PrintBinary().
x >>= 1;
This uses the right shift operator >> to rotate x by one bit to the right. This is exactly the same as dividing by 2 and many compilers use shift operations to optimize integer division. You could have used
x /= 2;
instead but I think >>= is more true to the meaning, and the compiler will probably generate right shift anyway.

The buffer is filled out in reverse. so PrintBinary(10,6) for example puts 010100 in the buffer then prints it out in reverse in the while loop. This makes it very easy to add leading zeros.

On the next page More about this example

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Example 1 - Using a Binary And to Extract Bits

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

All rights reserved.