1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

to_i(2) doesn't convert to decimal. It converts to an integer. Integers aren't decimal or binary or hexadecimal, they just are. Only string interpretations of numbers have a base, numbers themselves don't.
@JörgWMittag clarified the answer. WDYT?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.