在Perl中将字符串中的十六进制数转换为负数 [英] Converting hexadecimal numbers in strings to negative numbers, in Perl

查看:255
本文介绍了在Perl中将字符串中的十六进制数转换为负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在由Pe​​rl脚本解析的日志文件中,我有一堆数字表示为十六进制字符串,而我对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.

其中一些数字实际上是带负号的负数,即当以16位带符号整数表示时,为0xFFFE == -2.

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

有人可以告诉我从Perl中的字符串FFFE获取此数字的带符号表示形式的规范方法,还是以其他方式将我指向教程或其他资源?

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?

推荐答案

您可以使用 hex( )函数将十六进制转换为十进制,但会将输入解释为无符号值.为了弥补这一点,请将十进制值打包为无符号数量,然后将其打包为有符号数量:

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')));

"s"和"S"模板分别用于有符号和无符号16位数量.有关其他模板和使用信息,请参见 pack 函数的文档.

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.

这篇关于在Perl中将字符串中的十六进制数转换为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆