How do I convert decimal to hexadecimal in Perl?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

How can I convert a number, $d = 1024, in decimal to 0xFF in hex in Perl?

The d variable needs to be assigned to a different variable and be printed, so for readability I required it to be in hexadecimal format.

回答1:

1024 in decimal is not 0xFF in hex. Instead, it is 0x400.

You can use sprintf as:

my $hex = sprintf("0x%X", $d); 


回答2:

Caveat: sprintf overflows at 26419, on 32-bit even already at only 2329.

For large numbers, enable the lexical pragma bigint. as_hex is documented in Math::BigInt.

use bigint; my $n = 2**65; print $n->as_hex;   # '0x20000000000000000' 


回答3:

I put these snippets into Perl files in my $PATH:

Convert list of decimal numbers into hexadecimal and binary

for ($i = 0; $i < @ARGV; $i++) {     printf("%d\t= 0x%x\t= 0b%b\n", $ARGV[$i], $ARGV[$i], $ARGV[$i]); } 

Convert list of hexadecimal numbers into decimal and binary

for ($i = 0; $i < @ARGV; $i++) {     $val = hex($ARGV[$i]);     printf("0x%x\t= %d\t= 0b%b\n", $val, $val, $val); } 

Convert list of binary numbers into decimal and hexadecimal

for ($i = 0; $i < @ARGV; $i++) {     # The binary numbers you type must start with '0b'     $val = oct($ARGV[$i]);     printf("0b%b\t= %d\t= 0x%x\n", $val, $val, $val); } 


回答4:

You can use the classical printf().

printf("%x",$d); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!