Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 930
Noby Fujioka Avatar asked Jun 29 '16 04:06

Noby Fujioka


People also ask

How do you convert a negative number to binary?

The simplest is to simply use the leftmost digit of the number as a special value to represent the sign of the number: 0 = positive, 1 = negative. For example, a value of positive 12 (decimal) would be written as 01100 in binary, but negative 12 (decimal) would be written as 11100.

How do you check if a number is negative in Ruby?

The negative?() is an inbuilt method in Ruby returns a boolean value. It returns true if the number is a negative one, else it returns false.

How do you convert a number to a binary string?

toBinaryString(int i) To convert an integer to binary, we can simply call the public static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.


1 Answers

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"
like image 141
falsetru Avatar answered Nov 16 '22 21:11

falsetru