Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print the bits without using a loop in C?

Right now, what I do is this:

void print_bits(unsigned int x)
{
    int i;
    for(i=WORD_SIZE-1; i>=0; i--) {
        (x & (1 << i)) ? putchar('1') : putchar('0');
    }
    printf("\n");
}

Also, it would be great to have a solution independent of word size (currently set to 32 in my example).

like image 597
Nikhil Vidhani Avatar asked Sep 07 '14 10:09

Nikhil Vidhani


People also ask

How to print array without loop in C?

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).

How do I print a memory?

To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.


2 Answers

How about this:

void print2Bits(int a) {
    char* table[] = {
        "00",
        "01",
        "10",
        "11"
    };
    puts(table[a & 3]);
}

void printByte(int a) {
    print2Bits(a >> 6);
    print2Bits(a >> 4);
    print2Bits(a >> 2);
    print2Bits(a);
}

void print32Bits(int a) {
    printByte(a >> 24);
    printByte(a >> 16);
    printByte(a >> 8);
    printByte(a);
}

I think, that's the closes you'll get to writing a binary number without a loop.

like image 143
cmaster - reinstate monica Avatar answered Oct 04 '22 02:10

cmaster - reinstate monica


You may try itoa. Although it is not in standard C lib, it is available in most C compilers.

void print_bits(int x)
{
    char bits[33];
    itoa(x, bits, 2);
    puts(bits);
}
like image 30
ACcreator Avatar answered Oct 04 '22 00:10

ACcreator