Noby Fujioka
Noby Fujioka

Reputation: 1824

How to convert negative integers to binary in Ruby

Question 1: I cannot find a way to convert negative integers to binary in the following way. I am supposed to convert it like this.

-3 => "11111111111111111111111111111101"

I tried below:

sprintf('%b', -3) => "..101" # .. appears and does not show 111111 bit.

-3.to_s(2) => "-11" # This just adds - to the binary of the positive integer 3.

Question 2: Interestingly, if I use online converter, it tells me that binary of -3 is "00101101 00110011".

What is the difference between "11111111111111111111111111111101" and "00101101 00110011"?

Upvotes: 5

Views: 1333

Answers (2)

Gagan Gami
Gagan Gami

Reputation: 10251

Try:

> 32.downto(0).map { |n| -3[n] }.join
#=> "111111111111111111111111111111101

Note: This applies to negative number's only.

Upvotes: 1

falsetru
falsetru

Reputation: 369074

Packing then unpacking will convert -3 to 4294967293 (232 - 3):

[-3].pack('L').unpack('L')
=> [4294967293]

sprintf('%b', [-3].pack('L').unpack('L')[0])
# => "11111111111111111111111111111101"

sprintf('%b', [3].pack('L').unpack('L')[0])
# => "11"

Upvotes: 11

Related Questions