You are here:

C/How to print bit values

Advertisement


Question
This question was asked in a test. I was asked to receive a char and to print its 8th bit(1 or 0)? I was able to mask and get the 8th bit, but was not able to print the bit? If 255 is the input, the result should be 1. But I was not able to print 1. The output was 80. By right shifting I can print 1. But is there any other way to print bit values.

Answer
Dear Vipin!

 i hope i have already answered this kind of question , both in case of integer and char !

here i will give you some code  , ( What i actually written for integers but modified of char ) this code will display all the 8 bits of a char value and specifically the 8th bit will be set to 1 if your value is 255  , check it out !

// here is the code !
#include<iostream.h>
#include<conio.h>

void showbits( char a);
void main()
{
  char a = 255;
  clrscr();

  showbits(a);
  getch();
}

void showbits(char a)
{
  int i  , k , mask;

  for( i =7 ; i >= 0 ; i--)
  {
     mask = 1 << i;
     k = a & mask;
     if( k == 0)
        cout<<"0 ";
     else
        cout<<"1 ";
  }
}

note :
 You can alter this program to check out the bit patterns of signed , unsigned , long , int  and so on ..

regards !
Prince M. Premnath.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.