How do I easily convert a number, e.g. 0x616263
, equivalently 6382179
in base 10, into a string by dividing the number up into sequential bytes? So the example above should convert into 'abc'
.
I've experimented with Array.pack but cant figure out how to get it to convert more than one byte in the number, e.g. [0x616263].pack("C*")
returns 'c'
.
I've also tried 0x616263.to_s(256)
, but that throws an ArgumentError: invalid radix. I guess it needs some sort of encoding information?
(Note: Other datatypes in pack like N
work with the example I've given above, but only because it fits within 4 bytes, so e.g. [0x616263646566].pack("N")
gives cdef
, not abcdef
)
This question is vaguely similar to this one, but not really. Also, I sort of figured out how to get the hex representation string from a character string using "abcde".unpack("c*").map{|c| c.to_s(16)}.join("")
, which gives '6162636465'
. I basically want to go backwards.
I don't think this is an X-Y problem, but in case it is - I'm trying to convert a number I've decoded with RSA into a character string.
Thanks for any help. I'm not too experienced with Ruby. I'd also be interested in a Python solution (for fun), but I don't know if its right to add tags for two separate programming languages to this question.