0

How encode sequence of bytes from ruby string into ruby string human-readable characters?

This is input string:

"\x127\x00\x06\x00\x00\x00\x01\x00\xA2\x8F"

So how parse this string into array with bytes,

and encode every element from array to ASCII character?

P.S. However, I can't find a way to roundtrip from bytes back to an array. I tried to use Array.pack with the U* option, but that doesn't work for multibyte characters.

8
  • 2
    Please give example of what you mean by "human-readable" (I can read your example just fine if I am to understand it as a Ruby string). Also, it is a good idea to show some code that you have so far, otherwise it takes more effort to answer your question (and less people will think to do so). Jan 30, 2014 at 14:20
  • may be this method will help you - ruby-doc.org/core-2.1.0/String.html#method-i-unpack .. But How I don't know.. :) Jan 30, 2014 at 14:22
  • Sorry to cast a close on this. I think if you knew what yu were looking for, you probably would not have needed to ask the question in the first place.
    – jww
    Jan 31, 2014 at 3:22
  • possible duplicate of How does string.unpack work in Ruby?
    – jww
    Jan 31, 2014 at 3:22
  • 1
    "string\xaa".each_byte.map {|b| "%c" % b } Jan 31, 2014 at 7:24

1 Answer 1

2

You can try something like:

"string\xaa".each_byte.map {|b| "%c(%x)" % [ b, b ] }.join( ' ' )
# => "s(73) t(74) r(72) i(69) n(6e) g(67) ª(aa)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.