c question: *printf'ing arrays
Giorgos Keramidas
keramida at ceid.upatras.gr
Sat Jul 4 07:17:20 UTC 2009
On Wed, 01 Jul 2009 00:06:05 +0200 (CEST), Alexander Best <alexbestms at math.uni-muenster.de> wrote:
> thanks for all the help. i decided to take the pill and coded all the
> fprintfs by hand. here's the result. usually i'd stick to a higher
> level languag, but i need C's inline assembly support:
>
> struct Header
> {
> u_int8_t rom_entry[4];
> u_int8_t nintendo_logo[156];
...
> fprintf(stderr, "\nNintendo Logo: 0x");
> for (i=0; i < sizeof(hdr->nintendo_logo); i++)
> fprintf(stderr, "%x", hdr->nintendo_logo[i]);
Note that %x will only print *one* digit for values smaller than 16,
i.e. printf("%x", 10) => "a", so it may be useful to use "%02x" instead.
> fprintf(stderr, "\nFixed Value: 0x");
> fprintf(stderr, "%x", hdr->fixed_val);
For multi-byte fields, it makes sense to print "0x" first and then
iterate. For single-byte values, it's probably a tiny bit faster to go
only _once_ through for *printf() family formatter, i.e.:
- fprintf(stderr, "\nFixed Value: 0x");
- fprintf(stderr, "%x", hdr->fixed_val);
+ fprintf(stderr, "\nFixed Value: 0x%x", hdr->fixed_val);
Another nit that I noticed is that your last line doesn't end with "\n":
> fprintf(stderr, "\nJoybus Entry Point: 0x");
> for (i=0; i < sizeof(hdr->joybus_entry); i++) fprintf(stderr, "%x",
> hdr->joybus_entry[i]);
Some terminal setups will *not* output the last line if it does not
finish properly with a "\n", so it may be worth editing the code to
avoid the "\nXXX" format idiom, and go for a format style that puts
"\n" at the _end_ of output lines:
fprintf(stderr, "Nintendo Logo: 0x");
for (i = 0; i < sizeof(hdr->nintendo_logo); i++)
fprintf(stderr, "%02x", hdr->nintendo_logo[i]);
fprintf(stderr, "\n");
fprintf(stderr, "Fixed Value: 0x%02x\n", hdr->fixed_val);
More information about the freebsd-hackers
mailing list