Is there a printf converter to print in binary format? Is there a printf converter to print in binary format? c c

Is there a printf converter to print in binary format?


Hacky but works for me:

#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"#define BYTE_TO_BINARY(byte)  \  (byte & 0x80 ? '1' : '0'), \  (byte & 0x40 ? '1' : '0'), \  (byte & 0x20 ? '1' : '0'), \  (byte & 0x10 ? '1' : '0'), \  (byte & 0x08 ? '1' : '0'), \  (byte & 0x04 ? '1' : '0'), \  (byte & 0x02 ? '1' : '0'), \  (byte & 0x01 ? '1' : '0') 
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));

For multi-byte types

printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",  BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));

You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to BYTE_TO_BINARY) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.


Print Binary for Any Datatype

// Assumes little endianvoid printBits(size_t const size, void const * const ptr){    unsigned char *b = (unsigned char*) ptr;    unsigned char byte;    int i, j;        for (i = size-1; i >= 0; i--) {        for (j = 7; j >= 0; j--) {            byte = (b[i] >> j) & 1;            printf("%u", byte);        }    }    puts("");}

Test:

int main(int argv, char* argc[]){    int i = 23;    uint ui = UINT_MAX;    float f = 23.45f;    printBits(sizeof(i), &i);    printBits(sizeof(ui), &ui);    printBits(sizeof(f), &f);    return 0;}


Here is a quick hack to demonstrate techniques to do what you want.

#include <stdio.h>      /* printf */#include <string.h>     /* strcat */#include <stdlib.h>     /* strtol */const char *byte_to_binary(    int x){    static char b[9];    b[0] = '\0';    int z;    for (z = 128; z > 0; z >>= 1)    {        strcat(b, ((x & z) == z) ? "1" : "0");    }    return b;}int main(    void){    {        /* binary string to int */        char *tmp;        char *b = "0101";        printf("%d\n", strtol(b, &tmp, 2));    }    {        /* byte to binary string */        printf("%s\n", byte_to_binary(5));    }        return 0;}