Perl Pack Unpack on Shell Variable

Dan*_*Dan 2 bash shell perl unpack pack

Ultimately my goal is to convert a hexdump of data to the correct floating point value. I have set up my shell script to isolate the individual hex values I need to look at and arrange them in the correct order for a little Endian float conversion.

To simplify everything, I'll bypass the code I have managed to get working, and I'll start with:

rawHex=0x41000000
echo $(perl -e 'print unpack "f", pack "L", $ENV{rawHex}')
Run Code Online (Sandbox Code Playgroud)

When I execute this code, the result is 0. However if I were to execute the code without attempting to pull the value of the shell variable:

echo $(perl -e 'print unpack "f", pack "L", 0x41000000')
Run Code Online (Sandbox Code Playgroud)

The result is 8, which is what I am expecting.

I'd appreciate any help on how I can update my Perl expression to properly interpret the value of the shell variable. Thanks.

ike*_*ami 5

export rawHex=0x41000000
perl -le'print unpack "f", pack "L", hex($ENV{rawHex})'
Run Code Online (Sandbox Code Playgroud)

如您所发现,您的代码不等同于以下代码:

perl -e 'print unpack "f", pack "L", 0x41000000'
Run Code Online (Sandbox Code Playgroud)

您的代码等效于以下内容:

perl -e 'print unpack "f", pack "L", "0x41000000"'
Run Code Online (Sandbox Code Playgroud)

"0x41000000"$ENV{rawHex}产生字符串 0x41000000。另一方面,0x41000000生产数量为十亿,九千万,五十九万四千四十。

要将数字的十六进制表示转换为它表示的数字,可以使用hex。只需替换$ENV{rawHex}hex($ENV{rawHex})

export rawHex=0x41000000
perl -le'print unpack "f", pack "L", hex($ENV{rawHex})'
Run Code Online (Sandbox Code Playgroud)

-l导致要添加到输出换行符,所以你不需要使用echol如果您实际上没有使用,请随时删除echo

生成代码(如先前答案中所建议)是一种可怕的做法。