Reputation: 37
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
Reputation: 114248
[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
Reputation: 2877
String#%
(via sprintf
):
'%032b' % 7
=> "00000000000000000000000000000111"
Upvotes: 5
Reputation: 121010
Use String#rjust
:
1.to_s(2).rjust(32, '0')
#⇒ "00000000000000000000000000000001"
Upvotes: 5