21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

leading “0x” if it exists. The exception is when there is whitespace. This function<br />

passes back the number of bytes written in its second parameter. If that parameter is<br />

negative, an error occurred.<br />

Discussion<br />

The spc_hex2bin( ) function shown in this section converts an ASCII string into a<br />

binary string. Spaces and tabs are ignored. A leading “0x” or “0X” is ignored. There<br />

are two cases in which this function can fail. First, if it sees a non-hexadecimal digit,<br />

it assumes that the string is not in the right format, and it returns NULL, setting the<br />

error parameter to ERR_NOT_HEX. Second, if there is an odd number of hex digits in the<br />

string, it returns NULL, setting the error parameter to ERR_BAD_SIZE.<br />

#include <br />

#include <br />

#include <br />

#define ERR_NOT_HEX -1<br />

#define ERR_BAD_SIZE -2<br />

#define ERR_NO_MEM -3<br />

unsigned char *spc_hex2bin(const unsigned char *input, size_t *l) {<br />

unsigned char shift = 4, value = 0;<br />

unsigned char *r, *ret;<br />

const unsigned char *p;<br />

if (!(r = ret = (unsigned char *)malloc(strlen(input) / 2))) {<br />

*l = ERR_NO_MEM;<br />

return 0;<br />

}<br />

for (p = input; isspace(*p); p++);<br />

if (p[0] = = '0' && (p[1] = = 'x' || p[1] = = 'X')) p += 2;<br />

while (p[0]) {<br />

switch (p[0]) {<br />

case '0': case '1': case '2': case '3': case '4':<br />

case '5': case '6': case '7': case '8': case '9':<br />

value |= (*p++ - '0')

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

Saved successfully!

Ooh no, something went wrong!