Confusing syntax

Can anyone help me?

And I did not understand the code below. It's very simple, but I do not know this syntax. The parts in bold were the ones that I had more difficulty.

Grateful,

Yuri.

1
2
3
4
5
6
7
8
#include <stdio.h>
int main(int argc, char* argv[]) {
    int v=17,j=1<<7,i;
    for (i=0;i<8;i++) {
        putchar(v & j ? '1' : '0');
        v<<=1;
    }
}

<< is a bit shift to the left. 1<<7 equals pow(2,7) which equals 128 or 10000000 in binary.
& performs a bitwise and on the two operands. So the result will be 128 if the 8th bit in v is set and 0 if it isn't (in the first iteration).
That result is converted to bool (false for 0, true for all other values) and is used as the condition for the ?: operator.
v is shifted one position to the left then, so that means that the former 7th bit is now the 8th bit.

So essentially this code displays the lower 8 bits of v as a binary number.
Last edited on
the stuff in the putchar, is a Ternary operation.. It's basically a stripped down IF statement.

putchar(v & j ? '1' : '0');
is basically the same as:
1
2
3
4
if (v & j)
    putchar('1');
else
    putchar('0');


Basically, (condition) ? (if true, this) : (otherwise, this)
Last edited on
<< is the "left shift" operator... it shifts bits x bits to the left.

so for example say you have the number 5. In binary, 5 = %00000101. So:

1
2
3
4
5    = %00000101 = 5
5<<1 = %00001010 = 10
5<<2 = %00010100 = 20
...


So 1<<7 is the same as 0x80 (or 128)


& is the "and" operator. It compares the bits of two values and results in 1 if both of the appropriate bits are set, and 0 if either or both bits are clear:

0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1

1
2
3
4
5
6
Example:  0x35 & 0x96 = 0x14 because:

0x35 = 00110101
0x96 = 10010100
===============
0x14 = 00010100


? and : operators are like a conditional thing:

1
2
3
4
5
6
7
putchar(v & j ? '1' : '0');

// the above is the same as below:
if(v & j)
  putchar('1');
else
  putchar('0');


So basically this whole program is just way to print a number in binary.

EDIT: doh, way too slow
Last edited on
Ah! Now I get it right! This was a question of a test that I did.
Thanks for the both explanations.
Topic archived. No new replies allowed.