2's Compliment in Ruby

For general discussion related FlowStone
Post Reply
User avatar
aronb
Posts: 154
Joined: Sun Apr 17, 2011 3:08 am
Location: Florida, USA
Contact:

2's Compliment in Ruby

Post 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
KG_is_back
Posts: 1196
Joined: Tue Oct 22, 2013 5:43 pm
Location: Slovakia

Re: 2's Compliment in Ruby

Post 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

User avatar
aronb
Posts: 154
Joined: Sun Apr 17, 2011 3:08 am
Location: Florida, USA
Contact:

Re: 2's Compliment in Ruby

Post by aronb »

Thank You KG_is_back ! ! !

I initially did the > test incorrectly... DOH

Works perfectly now :D

Have a great weekend,

Aron
Post Reply