21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.3 Representing Binary Keys (or Other Raw<br />

Data) as Hexadecimal<br />

<strong>Problem</strong><br />

You want to print out keys in hexadecimal format, either for debugging or for easy<br />

communication.<br />

Solution<br />

The easiest way is to use the “%X” specifier in the printf() family of functions. In<br />

C++, you can set the ios::hex flag on a stream object before outputting a value, then<br />

clear the flag afterward.<br />

Discussion<br />

Here is a function called spc_print_hex() that prints arbitrary data of a specified<br />

length in formatted hexadecimal:<br />

#include <br />

#include <br />

#define BYTES_PER_GROUP 4<br />

#define GROUPS_PER_LINE 4<br />

/* Don't change these */<br />

#define BYTES_PER_LINE (BYTES_PER_GROUP * GROUPS_PER_LINE)<br />

void spc_print_hex(char *prefix, unsigned char *str, int len) {<br />

unsigned long i, j, preflen = 0;<br />

if (prefix) {<br />

printf("%s", prefix);<br />

preflen = strlen(prefix);<br />

}<br />

for (i = 0; i < len; i++) {<br />

printf("%02X ", str[i]);<br />

if (((i % BYTES_PER_LINE) = = (BYTES_PER_LINE - 1)) && ((i + 1) != len)) {<br />

putchar('\n');<br />

for (j = 0; j < preflen; j++) putchar(' ');<br />

}<br />

else if ((i % BYTES_PER_GROUP) = = (BYTES_PER_GROUP - 1)) putchar(' ');<br />

}<br />

putchar('\n');<br />

}<br />

120 | Chapter 4: Symmetric Cryptography Fundamentals<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!