tags:

views:

21622

answers:

17

I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?

I am running gcc.

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

You can not do this, as far as I know, using printf.

You could, obviously, write a helper method to accomplish this, but that doesn't sound like the direction you're wanting to go.

Ian P
A: 

There is no formating function in the C standard library to output binary like that. All the format operation the printf family supports are towards human readable text.

Florian Bösch
A: 

There isn't a format predefined for that. You need to transform it yourself to a string and then print the string.

rslite
A: 

A quick Google search produced this page with some information that may be useful:

http://forums.macrumors.com/archive/index.php/t-165959.html

Ian P
+4  A: 

Some runtimes support "%b" although that is not a standard.

Also see here for an interesting discussion:

http://bytes.com/forum/thread591027.html

HTH

rlerallut
This is actually a property of the C runtime library, not the compiler.
cjm
+1  A: 

No standard and portable way.

Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.

wnoise
+10  A: 

There isn't a binary conversion specifier in glibc normally.

It is possible to add custom conversion types to the printf() family of functions in glibc. See register_printf_function for details. You could add a custom %b conversion for your own use, if it simplifies the application code to have it available.

Here is an example of how to implement a custom printf formats in glibc.

DGentry
+15  A: 

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 = 256; 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;
}
EvilTeach
good answer.I like these kind of straight forward answers. thank u
Manoj Doubts
You are very welcome. Thanks for the vote up.
EvilTeach
This is certainly less "weird" than custom writing an escape overload for printf. It's simple to understand for a developer new to the code, as well.
Furious Coder
tomlogic
@tomlogic - I understand your viewpoint, but the question suggests that Brian may be a beginner, the use of strcat vs ()?: is more likely to be within his experience.
EvilTeach
@EvilTeach: You're using a ternary operator yourself as a parameter to `strcat()`! I agree that `strcat` is probably easier to understand than post-incrementing a dereferenced pointer for the assignment, but even beginners need to know how to properly use the standard library. Maybe using an indexed array for assignment would have been a good demonstration (and will actually work, since `b` isn't reset to all-zeros each time you call the function).
tomlogic
Lol, Ya Tom.... It's been a long day.
EvilTeach
Random: The binary buffer char is static, and is cleared to all zeros in the assignment. This will only clear it the first time it's run, and after that it wont clear, but instead use the last value.
markwatson
@random: Good Catch.
EvilTeach
A: 
quinmars
+2  A: 
const char* byte_to_binary( int x )
{
    static char b[8] = {0};

    for (int z=128,y=0; z>0; z>>=1,y++)
    {
        b[y] = ( ((x & z) == z) ? 49 : 48);
    }

    return b;
}
Clearer if you use `'1'` and `'0'` instead of `49` and `48` in your ternary. Also, `b` should be 9 characters long so the last character can remain a null terminator.
tomlogic
A: 

Even for the runtime libraries that DO support %b it seems it's only for integer values.

If you want to print floating-point values in binary, I wrote some code you can find at http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/ .

Rick Regan
+2  A: 
mrwes
+1  A: 

Hacky but works for me:

#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(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 "BYTETOBINARYPATTERN, BYTETOBINARY(byte));

For multi-byte types

printf("M: "BYTETOBINARYPATTERN" "BYTETOBINARYPATTERN"\n",
  BYTETOBINARY(M>>8), BYTETOBINARY(M));

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

William Whyte
And has the advantage also to be invocable multiple times in a `printf` which the ones with `static` buffers can't.
tristopia
A: 
void print_ulong_bin(const unsigned long * const var, int bits) {
        int i;

        #if defined(__LP64__) || defined(_LP64)
                if( (bits > 64) || (bits <= 0) )
        #else
                if( (bits > 32) || (bits <= 0) )
        #endif
                return;

        for(i = 0; i < bits; i++) { 
                printf("%lu", (*var >> (bits - 1 - i)) & 0x01);
        }
}

should work - untested.

olli
A: 

Print Binary for Any Datatype

//assumes little endian
void printBits(size_t const size, void const * const ptr)
{
    unsigned char *b = (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("");
}

golfed

void p(int s,void* p){int i,j;for(i=s-1;i>=0;i--)for(j=7;j>=0;j--)printf("%u",(*((unsigned char*)p+i)&(1<<j))>>j);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;
}
Shiftbit
A: 
void PrintBinary( int Value, int Places, char* TargetString)
{
    int Mask;

    Mask = 1 << Places;

    while( Places--) {
        Mask >>= 1; /* Preshift, because we did one too many above */
        *TargetString++ = (Value & Mask)?'1':'0';
    }
    *TargetString = 0; /* Null terminator for C string */
}

The calling function "owns" the string...:

char BinaryString[17];
...
PrintBinary( Value, 16, BinaryString);
printf( "yadda yadda %s yadda...\n", BinaryString);

Depending on your CPU, most of the operations in PrintBinary render to one or very few machine instructions.

Adam
A: 
rakesh jha