Monday, March 28, 2011

Converting binary data to string in ruby

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

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

    require 'base64'
    
    str = Base64.encode64(data)
    
    Brent.Longborough : 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
  • Another way to play with binary data is String#unpack.

    LK : Thanks - unpack('H*') did the job.

0 comments:

Post a Comment