Forum: Ruby Re: Converting Bytes to a Negative Integer

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D030415ddde3289040ff66e88853716c?d=identicon&s=25 Harris Reynolds (Guest)
on 2007-02-15 16:33
(Received via mailing list)
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 Gray 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 Ziegler * halostatue@gmail.com * http://www.halostatue.ca/
* austin@halostatue.ca * http://www.halostatue.ca/feed/
* austin@zieglers.ca



____________________________________________________________________________________
Cheap talk?
Check out Yahoo! Messenger's low PC-to-Phone call rates.
http://voice.yahoo.com
31ab75f7ddda241830659630746cdd3a?d=identicon&s=25 Austin Ziegler (austin)
on 2007-02-15 19:34
(Received via mailing list)
On 2/15/07, Harris Reynolds <hreynolds2@yahoo.com> 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
This topic is locked and can not be replied to.