From: Ken Bloom Date: 2008-01-11T10:10:03+09:00 Subject: Re: Question about Hex => Signed Int On Thu, 10 Jan 2008 13:19:46 -0500, Joel VanderWerf wrote: > Tim Conner wrote: >> Thanks for that. Is there a ruby function which I can pass a hex >> number and it works out if it is +/- and then returns the correct >> decimal value? > > Convert to unsigned first, like above, then do something like this: > > length = 32 # in bits; you have to choose this > > mid = 2**(length-1) > max_unsigned = 2**length > to_signed = proc {|n| (n>=mid) ? n - max_unsigned : n} > > p to_signed["0xFF467A7B".to_i(16)] > p to_signed["0x38CFEF".to_i(16)] > > See http://en.wikipedia.org/wiki/Twos_complement. Why go through all the trouble to make this a proc? --Ken -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/