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"
?
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With