1

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.

3 Answers 3

5

Use String#rjust:

1.to_s(2).rjust(32, '0')
#⇒ "00000000000000000000000000000001"
Sign up to request clarification or add additional context in comments.

Comments

5

String#% (via sprintf):

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

Comments

0

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"

Comments

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.