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.

}<br />

break;<br />

default:<br />

if (isspace(p[0])) p++;<br />

else {<br />

*l = ERR_NOT_HEX;<br />

free(ret);<br />

return 0;<br />

}<br />

}<br />

if ((shift = (shift + 4) % 8) != 0) {<br />

*r++ = value;<br />

value = 0;<br />

}<br />

}<br />

if (!shift) {<br />

*l = ERR_BAD_SIZE;<br />

free(ret);<br />

return 0;<br />

}<br />

*l = (r - ret);<br />

return (unsigned char *)realloc(ret, *l);<br />

}<br />

4.5 Performing Base64 Encoding<br />

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

You want to represent binary data in as compact a textual representation as is reasonable,<br />

but the data must be easy to encode and decode, and it must use printable<br />

text characters.<br />

Solution<br />

Base64 encoding encodes six bits of data at a time, meaning that every six bits of<br />

input map to one character of output. The characters in the output will be a numeric<br />

digit, a letter (uppercase or lowercase), a forward slash, a plus, or the equal sign<br />

(which is a special padding character).<br />

Note that four output characters map exactly to three input characters. As a result, if<br />

the input string isn’t a multiple of three characters, you’ll need to do some padding<br />

(explained in the “Discussion” section).<br />

Discussion<br />

The base64 alphabet takes 6-bit binary values representing numbers from 0 to 63<br />

and maps them to a set of printable ASCII characters. The values 0 through 25 map<br />

to the uppercase letters in order. The values 26 through 51 map to the lowercase letters.<br />

Then come the decimal digits from 0 to 9, and finally + and /.<br />

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

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Performing Base64 Encoding | 123

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

Saved successfully!

Ooh no, something went wrong!