Fleur
Fleur

Reputation: 59

Convert binary string to hexadecimal in Ruby

What is the most efficient way to convert a binary string into hexadecimal? I'm trying to do something like this:

a = '1010'    #Binary

and then to become

a = 'A'       #Hexa

Upvotes: 1

Views: 1939

Answers (1)

Pascal
Pascal

Reputation: 8637

You can convert it to an integer first, hinting that the string is binary (to_i(2)), then to hexadecimal (to_s(16)

"1010".to_i(2).to_s(16) # => 'a'

If you need it in uppercase, you can call upcase on the resulting string.

Upvotes: 4

Related Questions