shivashankar shivashankar - 5 months ago 23
Ruby Question

Signed 2's complement for a hexadecimal number

How can I convert a hexadecimal number for instance

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

['C4D81633'.scan(/[0-9a-f]{2}/i).reverse.join].pack('H*').unpack('l')


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

Answer

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
end

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