I know the answer to this program but I don't understand why?

0

I understand there is an increment of ii and x shifts left, but how does it go from 1 to being 3? Then from 13(D) to being 69? and so on...

#include <stdio.h>
int main()
{
    int x = 1;
    int ii;
    for (ii = 0; ii < 8; ii++) {
        x = (x << ii) | 1;
        printf("0x%.8X\n", x);
    }
    return (0);
}

and This is the output

0x00000001

0x00000003

0x0000000D

0x00000069

0x00000691

0x0000D221

0x00348841

0x1A442081 
c
asked on Stack Overflow Feb 18, 2019 by DontHurtMe • edited Feb 18, 2019 by rsjaffe

1 Answer

3

Just write everything on a paper in binary to understand it, like that:

1 = 0000 0001

i:1 ... 0000 0010 | 0000 0001 = 0000 0011 (hex: 3)

i:2 ... 0000 1100 | 0000 0001 = 0000 1101 (hex: d)

i:3 ... 0110 1000 | 0000 0001 = 0110 1001 (hex: 69)

i:4 ... etc.

answered on Stack Overflow Feb 19, 2019 by A.B.

User contributions licensed under CC BY-SA 3.0