help me understand dec to bin work

like this:

1
2
3
4
5
unsigned int uiNum = 38;

for(int i = 31; i >= 0; --i) {
    cout << (((uiNum >> i) % 2) ? '1' : '0');
}


I know that unsigned int have 32 bits, what does each bit % 2 mean, I think whether 1, or 0 % 2, the result is larger than 0 . maybe I'm wrong, because thik works.
>> does not give you a 'bit'. "uiNum >> i" is equivalent to "uiNum/ (2i)"

% 2 gives the parity of a number, therefore what its least significant bit is (0 or 1)
The opeartor % returns the remainder of division. For example 3 % 2 == 1 and 4 % 2 == 0

It can be writtten simpler

cout << (((uiNum >> i) % 2) + '0');

or

cout << (((uiNum >> i) & 1 ) + '0');

Topic archived. No new replies allowed.