Solving old problems: ASCII conversion
Sterling Camden
In a perfect world, all characters would be in Unicode, and all software would know how to deal with them. Although Unicode adoption has grown, especially on the web, there’s still a lot of software out there that uses good old ASCII. As a developer, I still regularly need to convert between ASCII and some numeric format — usually decimal or hexadecimal, but sometimes even octal or binary. I used to refer to this online ASCII table, but waiting for the page to load and then visually finding the desired entry all take time — a few seconds at least.
Then I realized that I could perform most conversions at a shell prompt. For instance, to get the numeric value of the character ‘A’, you can use Ruby:
$ ruby -e "print ?A"
But I wanted something with a little less typing that would be easier to remember. So I created a Ruby script named ‘ascii’, which you can download below or grab from the BitBucket repository.
If you invoke it without arguments, you get the full ASCII table. If you supply arguments, they’re evaluated. If they result in numeric values, then you get the equivalent ASCII values. Otherwise, you get the values of each character in the argument. You can also override the numeric evaluation and specify that you want all arguments treated as string using the -s option. For each value the script outputs, you get the decimal, octal, hexadecimal, and character representations.
ASCII only goes up to 255 in its 8-bit form, but this script actually allows higher values. In that case, the character representation will be modulo 256 — but you can use this ‘feature’ to perform decimal/octal/hex/binary conversions. Since ascii accepts any numeric argument, you can prefix it with 0b for binary, 0o (or just 0) for octal, or 0x for hex. You can even do arithmetic evaluations like ‘?A+32′ (the value of ‘A’ plus 32) or ’65|0×20′ (another way of getting the same value). Note the quotes to prevent the shell from evaluation the ? or the |.
See the included man page for details.
Posted in Ruby |
1 Comment » RSS 2.0 | Sphere it!





