Page 1 of 1

2's Compliment in Ruby

Posted: Tue Nov 03, 2015 4:04 am
by aronb
Hi,

How do you do 2's Compliment conversion in Ruby ?

I have a 16bit 2's compliment number that needs to be signed integer -32768 to 32767

thanks for any input...

Aron

Re: 2's Compliment in Ruby

Posted: Tue Nov 03, 2015 11:39 am
by KG_is_back
Numbers in ruby are 2's compliment. If I assume correctly, your 16bit signed number is being displayed in unsigned format? If that is correct, simply subtract 2^16 in number is above or equal 2^15

Code: Select all

def unsigned_to_signed(x,bitdeapth)
if x>2**(bitdeapth-1)
x-2**bitdeapth
else
x
end
end


Re: 2's Compliment in Ruby

Posted: Fri Nov 06, 2015 7:18 pm
by aronb
Thank You KG_is_back ! ! !

I initially did the > test incorrectly... DOH

Works perfectly now :D

Have a great weekend,

Aron