1.4 Converting ASII Codes into Characters
TechniqueUse chr() and ord() or sprintf() to convert back and forth: <?php $letter = chr (67); // Upper case C $ascii_code = ord ($letter); // 67 $letter = sprintf ("%c", $ascii_code); // Upper case C ?> CommentsOn the surface, converting ASCII values seems to be a pretty useless task. When I was a beginning programmer (Perl at the time), I thought that it was pointless for people even to write these functions and explanations . However, there are many cases in which you do need to convert back and forth. For example, let's say that you have binary data stored in an ODBC database, and you want to extract it as a string, but (gasp) it is returned in ASCII codes instead of characters! If this happens, the chr() and ord() functions suddenly become incredibly useful. You can also try the unpack() function to help with the conversion. The chr() function takes one ASCII code and converts it to a character. The ord() function does the same thing in reverse; it takes a character and converts it to an ASCII code. For the code to convert an ASCII string, look at recipe 1.5. |