James Ko
James Ko

Reputation: 34489

How to printf binary data in C?

I'm relatively new to C. I have a binary buffer that I want to print to stdout, like so:

unsigned char buffer[1024];

Is there a way to use printf to output this to stdout? I took a look at the man page for printf, however there is no mention of an unsigned char*, only of const char* for %s.

I suppose I could loop over the buffer and do putchar(buffer[i]), however I think that would be rather inefficient. Is there a way to do this using printf? Should I use something like fwrite instead, would that be more appropriate?

Thanks.

edit: Sorry for the confusion, I'm not looking to convert anything to hexadecimal/binary notation, just write out the buffer as-is. For example, if I had [0x41 0x42 0x42 0x41] in the buffer then I would want to print "ABBA".

Upvotes: 2

Views: 12938

Answers (1)

James Ko
James Ko

Reputation: 34489

As @redneb said, fwrite should be used for this:

#include <stdio.h>

size_t size = sizeof(buffer); /* or however much you're planning to write */
fwrite(buffer, 1, size, stdout);

Upvotes: 5

Related Questions