#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');
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)
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.