How can I enclose an extension in perl?

In my code, I read data from an array of 16-bit values, where some of the data actually contains signed 32-bit variables (from a large number of systems). So I will do something like:

$value = $data[$i] << 16 | $data[$i+1]; 

This works fine on a 32-bit system, but when working on a 64-bit system, it will be interpreted as a positive number (two-complement as a 32-bit number). Of course, I can manually check if the high-order bit is set and subtract it, but it becomes a little awkward, especially since I would like the code to work on both 32 and 64-bit systems. Is there an easy and good way to do this?

+6
source share
1 answer

I would use pack and unpack :

 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 entire array at once:

 my @values = unpack('l>*', pack('n*', @data)); 
+5
source

Source: https://habr.com/ru/post/890582/


All Articles