How to convert an integer to bytes and back to an integer.
# argument: short integer to convert to two bytes # return: two bytes sub short_to_bytes { local @_ = unpack("C*",pack("L",shift)); (shift, shift); } # argument: two bytes to convert into an integer # return: short integer sub bytes_to_short { my $res = 0; $res |= $bytes[1] & 0xFF; $res <<= 8; $res |= $bytes[0] & 0xFF; return $res; }

Replies are listed 'Best First'.
Re: Int ->Bytes -> Int
by ikegami (Patriarch) on Sep 03, 2007 at 07:20 UTC
    bytes_to_short(short_to_bytes($x)) is not equal to $x on all platforms. Use v instead. (Using "L" to convert shorts is silly anyway.)

    Furthermore, "short" is a very ambiguous term. It doesn't necessarily mean 16 bits, and it definitely doesn't imply unsigned (as your code expects).

    sub uint16_to_bytes { my ($int) = @_; return unpack('C2', pack('v', $int)); } sub bytes_to_uint16 { my ($lo, $hi) = @_; return unpack('v', pack('C2', $lo, $hi)); } sub int16_to_bytes { my ($int) = @_; return unpack('C2', pack('v', unpack('S', pack('s', $int)))); } sub bytes_to_int16 { my ($lo, $hi) = @_; return unpack('s', pack('S', unpack('v', pack('C2', $lo, $hi)))); }
Re: Int ->Bytes -> Int
by bruceb3 (Pilgrim) on Sep 03, 2007 at 06:28 UTC
    Cool. Is there a line missing bytes_to_short subroutine? Where is @bytes initialized?