HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Machine independent C library for printing the binary representation of data types to stdout

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thestdoutindependentprintingbinaryforlibrarytypesmachinerepresentation

Problem

I'm curious as to peoples thoughts on this small library I have made. I noticed there are no functions in the C standard library to accomplish this task.

I have tried to make the code machine independent. If anyone has access to machines where short != 2 byte, int != 4 byte, long != 8 byte or where bytes themselves are not 8 bits. I would be curious as to the test results.

GitHub

The current functions for printing the binary representations are all slight modifications of the below:

#include 
#include 

void printcb(char n)
{
    int i;
    int type_bits = CHAR_BIT;
    int mask = 1 << type_bits - 1;

    for (i = 0; i < type_bits; ++i) {
        if (n & mask)
            putc('1', stdout);
        else
            putc('0', stdout);
        n <<= 1;
    }
    putc('\n', stdout);
}

Solution

-
You can just call putchar(), which automatically prints to stdout:

putchar('1');


-
The conditionals can instead be a ternary statement within putchar():

putchar(n & mask ? '1' : '0');


putchar is often better suited for single-character output. putchar only has to pass a character directly to the output. This particular code isn't exactly performance-critical but it's useful to acquire good coding habits from the beginning.

Code Snippets

putchar('1');
putchar(n & mask ? '1' : '0');

Context

StackExchange Code Review Q#110218, answer score: 4

Revisions (0)

No revisions yet.