Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hexadecimal numbers in strings to negative numbers, in Perl

I have a bunch of numbers represented as hexadecimal strings in log files that are being parsed by a Perl script, and I'm relatively inexperienced with Perl.

Some of these numbers are actually signed negative numbers, i.e. 0xFFFE == -2 when represented as a 16-bit signed integer.

Can somebody please tell me the canonical way of getting the signed representation of this number from the string FFFE in Perl, or otherwise point me to a tutorial or other resource?

like image 335
Alex Marshall Avatar asked Jan 21 '10 18:01

Alex Marshall


People also ask

Can a hexadecimal number be negative?

A hex number is always positive (unless you specifically put a minus sign in front of it). It might be interpreted as a negative number once you store it in a particular data type. Only then does the most significant bit (MSB) matter, but it's the MSB of the number "as stored in that data type".

How do you convert negative hexadecimal to positive hexadecimal?

The hexadecimal value of a negative decimal number can be obtained starting from the binary value of that decimal number positive value. The binary value needs to be negated and then, to add 1. The result (converted to hex) represents the hex value of the respective negative decimal number.


2 Answers

You can use the hex() function to convert from hexadecimal to decimal, but it interprets the input as an unsigned value. To compensate for that, pack the decimal value as an unsigned quantity and unpack it as a signed one:

my $num = unpack('s', pack('S', hex('FFFE')));

The 's' and 'S' templates are for signed and unsigned 16-bit quantities, respectively. See the documentation for the pack function for other templates and usage information.

like image 96
Michael Carman Avatar answered Oct 26 '22 00:10

Michael Carman


print unpack('s>', pack('H4', 'FFFE'));
-2
like image 21
Oleg V. Volkov Avatar answered Oct 25 '22 23:10

Oleg V. Volkov