How to convert a character to its corresponding hexadecimal in the ASCII Ruby table?

Asked

Viewed 181 times

1

I am using Ruby and have the string "AwX" in hexadecimal. I can write to the screen using the following command:

puts "\x41\x77\x58"

But I want to do the reverse: I have a string "AwX", but I want to retrieve the hexadecimals of these characters (whether as array of strings, single string or other formats) and write the result on the screen (with the characters being represented in the hexadecimal notation, as being "0x41", "x41" or other formats). How this character conversion can be performed?

I tried to use the functions string.hex and string.to_i:

puts "A".hex # esperava "x41", mas foi retornado 10
puts "A".to_i(base=16) # esperava "x41", mas foi retornado 10
puts "A".to_i.to_s(16) # esperava "x41", mas foi retornado 0

1 answer

3


You can use the method codepoints, which returns an array with the numeric values corresponding to the characters of the string, and then just convert them to the desired format:

puts "AwX".codepoints.map { |i| "0x" + i.to_s(16) }.join()

puts "AwX".codepoints.map { |i| format("\\x%X", i)}.join()

In the first case I used the prefix 0x and to_s to convert to hexa, and in the second, I used the prefix \x and format to print the number in hexa (only to show two different ways of doing).

In both cases I used join at the end, to join everything in a single string. The output is:

0x410x770x58
\x41\x77\x58

The methods you used consider that the string represents a number in base 16 (so returns 10, because 10 in hexadecimal is equal to A).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.