Ruby - How to convert ASCII decimal (byte) values to characters

Problem: You have a byte value, or a string of byte values, and you want to use a Ruby script to convert each byte to its equivalent ASCII character.

Solution

I just ran into this problem while working on a script to remove binary/garbage characters from a Unix text file. In short, the file had a bunch of binary "garbage" characters in it, and I wanted a clean version of the file that contained only printable ASCII characters in it.

The solution is to use the chr method on each byte value, like this:

puts 65.chr

which prints:

A

A few more examples

Here are a few more examples, in the form of some slightly-commented output from a Ruby irb session:

>> 65.chr
=> "A"

>> 97.chr
=> "a"

# tab
>> 9.chr
=> "\t"

# linefeed
>> 10.chr
=> "\n"

# form feed
>> 12.chr
=> "\f"

# carriage return
13.chr
=> "\r"

# tilde, the last printable character
>> 126.chr
=> "~"

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.