rubybinarytwos-complement

How to convert two's complement binary to decimal in ruby?


What is the easiest way to convert a two's complement binary to decimal? For example, if I normally convert a string such as"1001" to decimal I'll get a 9. But I'm actually trying to get a simple -7. What do you guys suggest?,


Solution

  • From your question it looks like you are using a 4 bit system.
    This might work for you, I got the results you were asking for.
    Here are two functions, one for 4 bit and one for 16 bit twos' complement.

      # For 4 bit
      def convert_4bit_to_signed_binary(binary)
        binary_int = binary.to_i(2)
        if binary_int >= 2**3 # for 4 bit
          return binary_int - 2**4
        else
          return binary_int
        end
      end
    
      # For 16 bit
      def convert_16bit_to_signed_binary(binary)
        binary_int = binary.to_i(2)
        if binary_int >= 2**15 # for 16 bit
          return binary_int - 2**16
        else
          return binary_int
        end
      end
    
      i = convert_4bit_to_signed_binary('1001')   # will give -7
      j = convert_16bit_to_signed_binary('1001')  # will give 9
    
      puts i
      puts j  
    

    Let me know if this works for you?