Alexander Wisowaty
Alexander Wisowaty

Reputation: 37

Ruby: convert integer to 32 bit binary number (or string)

I want to convert a number, say 1, into a 32 bit binary number:

00000000000000000000000000000001  

how can I do this to ensure the full string is of length 32, no matter how small the number might be?

I had a sprintf working for 8 bit binary, but not sure how to make it 32.

Upvotes: 1

Views: 2161

Answers (3)

Stefan
Stefan

Reputation: 114248

Using pack and unpack1:

[1].pack('L>').unpack1('B*')
#=> "00000000000000000000000000000001"

L indicates 32-bit unsigned integer, > denotes big endian. B indicates bit string, * outputs all available bits.

This will wrap around when exceeding the 32-bit unsigned integer range:

[4_294_967_294].pack('L>').unpack1('B*') #=> "11111111111111111111111111111110"
[4_294_967_295].pack('L>').unpack1('B*') #=> "11111111111111111111111111111111"
[4_294_967_296].pack('L>').unpack1('B*') #=> "00000000000000000000000000000000"
[4_294_967_297].pack('L>').unpack1('B*') #=> "00000000000000000000000000000001"

Upvotes: 0

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

String#% (via sprintf):

'%032b' % 7
=> "00000000000000000000000000000111"

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Use String#rjust:

1.to_s(2).rjust(32, '0')
#⇒ "00000000000000000000000000000001"

Upvotes: 5

Related Questions