Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sign extend an integer in perl?

Tags:

perl

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?

like image 494
tengfred Avatar asked Jun 15 '11 07:06

tengfred


1 Answers

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));
like image 181
cjm Avatar answered Nov 01 '22 14:11

cjm