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.
Harris R. (Guest)
on 2007-02-15 17: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 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. * removed_email_address@domain.invalid * http://www.halostatue.ca/
* removed_email_address@domain.invalid * http://www.halostatue.ca/feed/
* removed_email_address@domain.invalid



____________________________________________________________________________________
Cheap talk?
Check out Yahoo! Messenger's low PC-to-Phone call rates.
http://voice.yahoo.com
Austin Z. (Guest)
on 2007-02-15 20:34
(Received via mailing list)
On 2/15/07, Harris R. <removed_email_address@domain.invalid> 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.