如何在Perl中将十六进制字符串转换为数字? [英] How can I convert hex strings into numbers in Perl?
问题描述
我最近编写了一个脚本,它解析了单个二进制字节月份字段的文本表示。
(不要问: - {)
在我放弃sprintf一段时间之后,做到这一点;
我们%月= qw / x01 1
x02 2
x03 3
x04 4
x05 5
x06 6
x07 7
x08 8
x09 9
x0a 10
x0b 11
x0c 12 /;
...
my $ month = $ months {$ text};
我逃避了,因为我只使用了12个数字,但有没有更好的方法
如果您有
$ hex_string =0x10;
您可以使用:
$ hex_val = hex($ hex_string);
您将得到: $ hex_val == 16
$ b
十六进制
不需要 0x
在字符串的开头。如果缺少,它仍会将十六进制字符串转换为数字。
-
0b
- binary -
0
- 八进制 -
0x
- 十六进制
I recently wrote a script which parsed a text representation of a single binary byte month field.
(Don't ask :-{ )
After fiddling with sprintf for a while I gave up and did this;
our %months = qw / x01 1
x02 2
x03 3
x04 4
x05 5
x06 6
x07 7
x08 8
x09 9
x0a 10
x0b 11
x0c 12 /;
...
my $month = $months{$text};
Which I get away with, because I'm only using 12 numbers, but is there a better way of doing this?
If you have
$hex_string = "0x10";
you can use:
$hex_val = hex($hex_string);
And you'll get: $hex_val == 16
hex
doesn't require the "0x
" at the beginning of the string. If it's missing it will still translate a hex string to a number.
You can also use oct
to translate binary, octal or hex strings to numbers based on the prefix:
0b
- binary0
- octal0x
- hex
这篇关于如何在Perl中将十六进制字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!