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?
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".
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.
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.
print unpack('s>', pack('H4', 'FFFE'));
-2
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