I'm not sure we're using the same terms on either side of the equation, so we may be answering the wrong questions. Could you explain what you want in more detail please?
#include <stdio.h>
int main()
{
unsigned char a,b;
a = 1 + 2 + 4 + 16 + 32 + 64 + 128;
b=1;
while(b<=128)
{
if(a & b)
printf("%d\n", b);
if(b == 128)
b = b + 1;
else
b = b * 2;
}
}
I'm using something like this code to mark each bit position with one of the powers of two and then comparing the byte with a combination of each power of two. Thanks for the help. I'm probably not very clear about what I'm talking about.
I still don't quite get what you want, no. Why would you want to 'mark' bit positions? You already know where they are, and can't even mark anywhere else.
Whatever it is, you can probably do it with bit shift.
int n;
printf("bit shift\n");
for(n=0; n<=7; n++) printf("1 << %d = %d\n", n, 1<<n);
In your original post, 0011 1001, is binary for 0x39 which is the ASCII value for 9; Shamrock hit the nail on the head -- you're reading from stdin and need to convert the ASCII into an iteger before you can treat it as such.
I think this does what you want: reads a number from stdin (doesn't do much error checking) then prints the bits.
#include "stdio.h"
#include "stdlib.h"
void show_bits( unsigned char byte )
{
int i;
printf( "%d =", (unsigned int) byte );
for( i = 0; i < 8; i++ ) // for each bit
{
printf( "%d", byte & 0x80 ? 1 : 0 ); // test the high order (left) bit and print 1 if on
byte <<= 1; // shift to the left 1 bit
}
printf( "\n" ); // final newline
}
int main( int argc, char **argv )
{
unsigned int value;
printf( "enter non-number or ctl-D to quit\n" );
for( ; ; )
{
printf( "enter a number (0-255): " );
if( scanf( "%u", &value ) <= 0 ) // read value converting it to unsigned
{
printf( "\n" );
exit( 0 );
}
if( value < 256 )
show_bits( (unsigned char ) value ); // typecast not necessary, but shows intent
else
printf( "%d is out of range for a byte\n", value );
}
}
return 0;