Alexander Popov
Alexander Popov

Reputation: 24885

How to return a fixed length binary representation of an integer in Ruby?

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.

Upvotes: 5

Views: 2645

Answers (3)

tihom
tihom

Reputation: 8003

Use the String#% method to format a string

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

Here is a reference for different formatting options.

Upvotes: 4

falsetru
falsetru

Reputation: 369044

Using String#rjust:

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

Upvotes: 8

sawa
sawa

Reputation: 168091

Use string format.

"%08b" % 1
# => "00000001"

Upvotes: 9

Related Questions