How to convert two's complement binary to decimal in ruby? -
what easiest way convert two's complement binary decimal? example, if convert string such as"1001" decimal i'll 9. i'm trying simple -7. guys suggest?,
from question looks using 4 bit system.
might work you, got results asking for.
here 2 functions, 1 4 bit , 1 16 bit twos' complement.
# 4 bit def convert_4bit_to_signed_binary(binary) binary_int = binary.to_i(2) if binary_int >= 2**3 # 4 bit return binary_int - 2**4 else return binary_int end end # 16 bit def convert_16bit_to_signed_binary(binary) binary_int = binary.to_i(2) if binary_int >= 2**15 # 4 bit return binary_int - 2**16 else return binary_int end end = convert_4bit_to_signed_binary('1001') # give -7 j = convert_16bit_to_signed_binary('1001') # give 9 puts puts j
let me know if works you?
Comments
Post a Comment