In my code, I am reading data from an array of 16-bit values, where some of the data really contains signed 32-bit variables (from a big-endian system). So I'll do something like:
$value = $data[$i] << 16 | $data[$i+1];
This works fine on a 32-bit system, but when running on a 64-bit system, this will be interpreted as a positive number (the twos-complement as a 32-bit number). Of course, I can manually check if the highest bit is set, and subtract, but it gets a bit clunky, especially since I would like the code to work both on 32 and 64-bit systems. Is there a simple and good way of doing this?
I'd use pack and unpack for this:
my @data = (0x12, 0x3456);
my $i = 0;
my $value = unpack('l>', pack('n2', @data[$i, $i+1]));
This has the advantage that you can process the whole array at once:
my @values = unpack('l>*', pack('n*', @data));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With