5

I know that I can use Fixnum#to_s to represent integers as strings in binary format. However 1.to_s(2) produces 1 and I want it to produce 00000001. How can I make all the returned strings have zeros as a fill up to the 8 character? I could use something like:

binary = "#{'0' * (8 - (1.to_s(2)).size)}#{1.to_s(2)}" if (1.to_s(2)).size < 8

but that doesn't seem very elegant.

3 Answers 3

9

Use string format.

"%08b" % 1
# => "00000001"
Sign up to request clarification or add additional context in comments.

Comments

8

Using String#rjust:

1.to_s(2).rjust(8, '0')
=> "00000001"

Comments

4

Use the String#% method to format a string

 "%08d" % 1.to_s(2)
 # => "00000001" 

Here is a reference for different formatting options.

1 Comment

Great Link and Nice answer(+1)

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.