On Wed, 9 Apr 2003 05:46:03 +0900, Philip Mak wrote:
> Is there a way to pack() a signed long in a portable fashion (i.e.
> it should work on both little endian and big endian machines)?
> 
> The pack() function has these options:
>   'l' => { :signed => true, :network => false }
>   'N' => { :signed => false, :network => true }
> 
> But I cannot find an option that is { :signed => true, :network =>
> true }!
> 
> So if I pack with 'l', it won't work on different architectures.
> And if I pack with 'N', it won't allow negative numbers.
> 
> For now, I think I have to pack with 'N', but add 2**32 before
> packing and subtract 2**32 after unpacking, but I think there
> ought to be a better way?

Why not pack it as:

  m = -1                        # => -1
  n = [m < 0 ? 1 : 0, m.abs].pack("N*")
    # => "\001\000\000\000\001\000\000\000"
  o = n.unpack("N*")
  p = o[1] * (o[0] ? -1 : 1)

Yes, it means you have to know the encoding on both sides, but it
seems less risky than adding 2**32.

-austin
-- Austin Ziegler, austin / halostatue.ca on 2003.04.08 at 22:45:34