Re: Converting Bytes to a Negative Integer

I really like the to_signed proc idea at the bottom of this message…
the procedure doesn’t work however in all cases… note the Ruby code
below:

bits = 32
max_unsigned = 2 ** bits
max_signed = 2 ** (bits - 1)
to_signed = proc { |n| (n >= max_signed) ? n - max_unsigned : n }

x = -123
s = [x].pack(“N”)
puts to_signed[s.unpack(“N”).first]

y = 7777777
s = [y].pack(“N”)
puts to_signed[s.unpack(“N”).first]

try converting 7777777 when you already have the bytes

z = “”
[129, 237, 173, 241].each { |e| z << e }
puts to_signed[z.unpack(“N”).first]

OUTPUT

ruby signed_test.rb
-123
7777777
-2115129871

Coverting the bytes of 7777777 yields a pretty nasty negative number in
this case.

~harris

On 2/14/07, James Edward G. II <james / grayproductions.net> wrote:

11111111
This is where I had trouble. I found the following:
I’m anxious to see the cross-platform solution for this…
Joel VanDerWerf had something that I’ll be adapting if I need it
elsewhere.

x = -123
s = [x].pack(“N”)

bits = 32
max_unsigned = 2 ** bits
max_signed = 2 ** (bits - 1)
to_signed = proc { |n| (n >= max_signed) ? n - max_unsigned : n }

puts to_signed[s.unpack(“N”).first]

I need it for unsigned->signed words, so:

x = -123
s = [x].pack(“n”)

bits = 16
max_unsigned = 2 ** bits
max_signed = 2 ** (bits - 1)
to_signed = proc { |n| (n >= max_signed) ? n - max_unsigned : n }

puts to_signed[s.unpack(“n”).first]

-austin

Austin Z. * [email protected] * http://www.halostatue.ca/


Cheap talk?
Check out Yahoo! Messenger’s low PC-to-Phone call rates.
http://voice.yahoo.com

On 2/15/07, Harris R. [email protected] wrote:

try converting 7777777 when you already have the bytes

z = “”
[129, 237, 173, 241].each { |e| z << e }
puts to_signed[z.unpack(“N”).first]

The bytes are wrong. The bytes for 7,777,777 in “N” format are [0,
118, 173, 241].

-austin