11

I have a string containing byte data.
How can I perform an in-place conversion to ascii string?

1
  • 1
    What sort of an ascii string do you want to see? A bit string ("0101110110"), hex ("0AFC43"), or just something marshalled into ascii to decode somewhere else? Commented Feb 5, 2009 at 14:32

3 Answers 3

15

Another way to play with binary data is String#unpack.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - unpack('H*') did the job.
suppose the binary data is a representation of arabic text.. (text which i'm receiving as some giberrish like قرآن.. how do I unpack it to look like it's original arabic (ie using some arabic encoding or something)?
Is there a JavaScript equivalent to this?
7

You can do so via using base64 which is a fairly universal way.

require 'base64'

str = Base64.encode64(data)

1 Comment

data needs to be convertible to String for this to work. Try, for example: irb(main):002:0> Base64.encode64(1234) TypeError: can't convert Fixnum into String
2

if u have a binary string lets say something like:

s = "01001101011011110111000101110101011001010110010101110100"

and u wanna convert it back to ascii text in Ruby u can do like:

s = "01001101011011110111000101110101011001010110010101110100"

(0..s.length-8).step(8) do |i|
    print s[i,8].to_i(base=2).chr
end

Hope this will help someone :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.