> On Mar 12, 2017, at 11:49 AM, Die Optimisten <inform / die-optimisten.net> wrote:
> 
> I have a data-file containing:
> \x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01,\x00\x00\x01,\x08\x02\x00\x00\x00\xf6\x1f\x19"\x00\x00\x00\tpHYs\x00\x00\x17 ...
> 
> How can I convert it to the binary data ( \n \r \xhex_to_char )
> wanted to use eval, but that doesn't work.
> 
> short example:
> a='\x44RX\x55\n'    => "\\x44X\\x55\\n"
> c="b=\\x44X\\x55\\n"        # I want the result "DRXU\n"
> eval c     # (eval):1: syntax error, unexpected $undefined
> 
> What does generate this error?
> 
> How can I let Ruby do the conversion (same as x="..." does)?  # something like f.read(...,"INTERPOLATE"), but even a function new_string=my_string.convert  would be sufficient.
> pack doesn't work because of mixed  chars, \n and \x ...
> 
> thank you
> Opti

One way to do it might be

    new_string = my_string
      .gsub('\r', "\r")
      .gsub('\n', "\n")
      .gsub(/\\x([[:xdigit:]]{2})/) { Integer("0x#{$1}").chr })

for example:

$ pry
[1] pry(main)> '\x44RX\x55\n'.
[1] pry(main)* gsub('\r', "\r").
[1] pry(main)* gsub('\n', "\n").
[1] pry(main)* gsub(/\\x([[:xdigit:]]{2})/) { Integer("0x#{$1}").chr }
=> "DRXU\ní╔

Hope this helps,

Mike



-- 

Mike Stok <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.







Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>