Friday, March 7, 2008

c/c++: binary representation of the numeric

I had some free time and remembered old task from the university: show numeric in binary representation. In my old days I'd probably write smth with divs and mods. The core of the algorithm was a mathematical transformation: 13 = 1101 = 23*1+22*1+21*0+20*1. Now I just have thought about the problem from other side:

    int n = 13; 

    for (int i=sizeof(n)*8-1;i>=0;--i)
        printf("%d", (n >> i)&1);

    return 0;
Here we are:
$gcc 1.c -o out -std=c99 -O2
Just fun =).

No comments: