Search code examples
cbit

The showbits() function


While reading a book called "Let us C" I read that a function showbit() exists which can show you the bits of the number. There wasn't any special header file mentioned for it. Searched for it on the internet and didn't found anything useful. Is there such a function? I want this to print the binary of decimal numbers. Else please give me a replacement function. Thanks


Solution

  • All integers are actually in binary in your computer. Its just that it is turned into a string that is the decimal representation of that value when you try to print it using printf and "%d". If you want to know what it looks like in some other base (e.g. base 2 or binary), you either have to provide the proper printf format string if it exists (e.g. "%x" for hex) or just build that string yourself and print it out.

    Here is some code that can build the string representation of an integer in any base in [2,36].

    #include <stdio.h>
    #include <string.h>
    
    char digits[]="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    void reverse(char* start, char* end)
    {
        for(end--;start<end;start++,end--)
        {
            char t=*start;
            *start=*end;
            *end=t;
        }
    }
    
    
    int base_change(int n, int base,char* buffer)
    {
        int pos=0;
        if (base>strlen(digits)) 
            return -1;
        while(n)
        {
            buffer[pos]=digits[n%base];
            n/=base;
            pos++;
        }
        buffer[pos]='\0';
        reverse(buffer,buffer+pos);
        return 0;
    }
    
    int main()
    {
        char buffer[32];
        int conv=base_change(1024,2,buffer);
        if (conv==0) printf("%s\n",buffer);
        return 0;
    }