Perl - convert hexadecimal to binary and use it as string

SLP*_*SLP 5 perl hex type-conversion bin

I am new to Perl and I have difficulties using the different types.

I am trying to get an hexadecimal register, transform it to binary, use it a string and get substrings from the binary string.

I have done a few searches and what I tried is :

my $hex = 0xFA1F;
print "$hex\n";
Run Code Online (Sandbox Code Playgroud)

result was "64031" . First surprise : can't I print the hex value in Perl and not just the decimal value ?

$hex = hex($hex);
print "$hex\n";
Run Code Online (Sandbox Code Playgroud)

Result was 409649. Second surprise : I would expect the result to be also 64031 since "hex" converts hexadecimal to decimal.

my $bin = printf("%b", $hex);
Run Code Online (Sandbox Code Playgroud)

It prints the binary value. Is there a way to transform the hex to bin without printing it ?

Thanks, SLP

JGN*_*GNI 2

让我们按顺序处理每一个混乱的地方

my $hex = 0xFA1F;
Run Code Online (Sandbox Code Playgroud)

这在 中存储了一个十六进制常量$hex,但 Perl 没有十六进制数据类型,因此尽管您可以编写十六进制常量以及二进制和八进制常量,但 Perl 会将它们全部转换为十进制。请注意,两者之间存在很大差异

my $hex = 0xFA1F;
Run Code Online (Sandbox Code Playgroud)

my $hex = '0xFA1F';
Run Code Online (Sandbox Code Playgroud)

第一个将数字存储到 $hex 中,当您打印出来时,您会得到一个十进制数字,第二个存储一个字符串,打印时会给出该字符串,0xFAF1但可以将其传递给hex()函数以转换为十进制。

$hex = hex($hex);
Run Code Online (Sandbox Code Playgroud)

hex 函数将字符串转换为十六进制数字并返回十进制值,到目前为止,它$hex仅被用作数字 Perl 将首先字符串化$hex,然后将字符串传递给hex()以转换该值十六进制转十进制。

所以到了解决方案。您几乎已经完成了printf(),有一个名为的函数sprintf(),它采用相同的参数,printf()但不是打印格式化值,而是将其作为字符串返回。所以你需要的是。

my $hex = 0xFA1F;
my $bin = sprintf("%b", $hex);
print $bin;
Run Code Online (Sandbox Code Playgroud)

技术说明:是的,我知道 Perl 在内部将所有数字存储为二进制,但我们不要去那里寻找这个答案,好吗?

  • 关于“*Perl 将它们全部转换为十进制*”,不。Perl 将它们转换为计算机可以理解的格式(2 的补码)。转换为十进制(数字的文本表示形式)是通过“print”完成的。 (3认同)
  • 我想说,完全错误的解释比其他任何解释都更容易造成混乱。 (2认同)