Binary format specifier in printf

Asked 2 years ago, Updated 2 years ago, 80 views

All I know is decimal, octal, hexadecimal output Is there a binary formatter?

I'm using gcc. I hope I can use it like the code below

printf("%d %x %o\n", 10, 10, 10); //"10 A 12\n"
print("%b\n", 10); //"%b\n"

printf c

2022-09-22 22:18

1 Answers

Because there is no binary format specifier, you must define and write it yourself.

#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)
{
    {
        /* String to int */
        char *tmp;
        char *b = "0101";

        printf("%d\n", strtol(b, &tmp, 2));
    }

    {
        /* Byte to String */
        printf("%s\n", byte_to_binary(5));
    }

    return 0;
}

Or

//Assume little endian
void 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] & (1<<j);
            byte >>= j;
            printf("%u", byte);
        }
    }
    puts("");
}

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;
}


2022-09-22 22:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.