0
votes

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

1
Two's Complement only makes sense if the highest bit is set to 1, and that's not the case here unless for some strange reason you're encoding this in 4 bits. - tadman
If you have four-bit two's-complement, "1001" would be -1, not -7. Therefore, would just doing if val > 8 then val = 8 - val work here? - Ken Y-N
@tadman not everyone can afford a 64-bit computer. This is mine.. - Cary Swoveland
@CarySwoveland Glad you got the memory upgrade so you can use lower-case letters. - tadman

1 Answers

4
votes

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