questions on a program

I am trying to understanding the following small program, but sort of confusing in some lines of codes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 int f(int n) {
 int c;
 for (c=0;n!=0;++c)
    n=n&(n-1); 
return c;
} 
int main() { 
  char str[1000];
  for (;scanf("%s",str)!=EOF;) {
      for (int i=0;str[i];++i) { 
       int x=f(str[i]); 
           printf("%c",x&1?'0':'1');
               for (int j=6;j>=0;--j) 
               putchar(((str[i]>>j)&1)+'0'); 
       } 
       puts("");
      } 
    return 0;
 }


In specific, I don't quite understand how the following two lines of code work?
printf("%c",x&1?'0':'1');

and
putchar(((str[i]>>j)&1)+'0');

Thanks.
Last edited on
The first outputs '0' if the least significant bit of x is 1 and '1' if it is 0.

The second divides the 8-bit number str[i] by 2^j, then looks at the resulting least significant
bit, which will be 0 or 1, and adds it to '0', which will result in either '0' or '1'. Or, in other words,
it outputs '1' if the jth bit of str[i] is 1 and '0' if the jth bit is 0.
x&1 is equivalent to x%2!=0, i.e. it evaluates to true if x is an odd number. Prints '0' if it is odd, '1' if it's even.
Second line shifts the value of str[i] (i.e. ascii value of current char) j bit positions to the right (equivalent to dividing by 2 to the power of j) and prints the least significant bit (or short: prints the bit value at position j).

Edit: ah, too late. Tried to figure out if f was doing anything useful before I submitted.
(without success, I might add)
Last edited on
printf("%c",x&1?'0':'1');

if (x and 1) return true it prints char(0) (in fact it prints shit!!!)
else
it prints char(1) (shit again.)
(ascii code 1 and 2 are not printable charracter.)

putchar(((str[i]>>j)&1)+'0');

shift right str[i] , j times then and it with 1 and then add 48 (ascii code of '0') to result and then print out the equivalent ascii code.
sourena wrote:
(ascii code 1 and 2 are not printable charracter.)

That's not what happens though. The characters 0/1 (i.e. the characters with the ascii values 48/49) are being printed.
Topic archived. No new replies allowed.