1

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".

James Ko
  • 32,215
  • 30
  • 128
  • 239
  • 4
    Yes, `fwrite` is the way to go. – redneb Sep 04 '16 at 23:44
  • 1
    You could use printf with "%x" to print each character in hexadecimal. – Mick Sep 04 '16 at 23:46
  • `printf` with a binary string might prove to be a mistake if you use `%s`, since `%s` will terminate on the first NUL character, even though NUL is often a valid value in these circumstances. – Myst Sep 04 '16 at 23:48
  • If you just want to write the binary data (i.e., the actual bytes, not some ASCII representation of the values), you can do that with `write(1, buffer, sizeof(buffer))` (1 is the file descriptor of stdout). (Don't do that if you're doing other `stdio` writes to `stdout`, though.) – Andy Schweig Sep 04 '16 at 23:50
  • `fwrite` is the counterpart to `fprintf` for raw binary data. They are both C library functions. `write` OTOH is the low level OS system call that is used to implement `fwrite` (and `fprintf` for that matter). `fwrite` (and `fprintf`) are buffered, `write` is not. I am not sure if `write` is portable, but `fwrite` is. – redneb Sep 05 '16 at 00:00
  • See [Is there a printf converter to print in binary format?](http://stackoverflow.com/q/111928/2410359) or maybe [this](http://stackoverflow.com/a/35367414/2410359) – chux - Reinstate Monica Sep 05 '16 at 03:08
  • @chux Sorry for the confusion, I'm not looking to convert anything to hexadecimal/binary notation, just write out the buffer as-is. I've updated my question to clarify this. – James Ko Sep 05 '16 at 14:45

1 Answers1

5

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);
James Ko
  • 32,215
  • 30
  • 128
  • 239