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

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

问题描述

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

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

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天全站免登陆