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

C Programming Tutorial - Low Level Operations

By , About.com Guide

4 of 10

More about Example 1

Showing PrintBinary(10,6)
The image shows 1010 in decimal which is the same as 10102 in binary. 10 is made up of 8 + 2, so there are 1s in the binary positions for 8 and 2 and 0s elsewhere. There are only 4 bits shown but if there were 8 then the values of those bit positions would be 128 64 32 16. The value of any bit position n where n varies from 0 to 31 or 63 is 2n. Anything raised to the power of 0 is always 1.

Because the value of d (the number of digits to output) is 6, this loops 6 times. Steps 5 and 6 are identical and just output 0 because x is already 0 after step 4. The red box highlights the output and shows how 010100 is output.

If you feel confident you can simplify this further with two changes. Turn the while into a for loop (with no initalizing part!) and condense the if into a one line statement. The brackets around the x & 1 are needed as + has a higher precedence than binary & so if you remove them, it will generate rubbish. This works because you can use ints and chars together in this way. The longer if statement is easier to understand and more portable and would be my preference

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

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

On the next page : An example of and, or and xor.

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. How Example 1 works

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

All rights reserved.