shivashankar shivashankar - 10 months ago 53
Ruby Question

Signed 2's complement for a hexadecimal number

How can I convert a hexadecimal number for instance

to signed 2's complement i.e
using Ruby? I tried


but the above code is not working well when I give input of length less than 8 characters.


I found the answer after googling... I add it as a method which is as follows

def convert_to_signed_twos_complement(integer_value, num_of_bits)
  length       = num_of_bits
  mid          = 2**(length-1)
  max_unsigned = 2**length
  (integer_value >= mid) ? integer_value - max_unsigned : integer_value

hex_to_convert = 'C4D81633'
convert_to_signed_twos_complement(hex_to_convert.hex, 16)

Note: the num_of_bits in method denote the max bit size of the binary you want