简体   繁体   中英

Perl Pack Unpack on Shell Variable

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}')

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')

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.

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

As you discovered, your code isn't equivalent to the following:

perl -e 'print unpack "f", pack "L", 0x41000000'

Your code is equivalent to the following:

perl -e 'print unpack "f", pack "L", "0x41000000"'

Like "0x41000000" , $ENV{rawHex} produces the string 0x41000000 . On the other hand, 0x41000000 produces the number one billion, ninety million, five hundred nineteen thousand and forty.

To convert the hex representation of a number into the number it represents, one uses hex . Simply replace $ENV{rawHex} with hex($ENV{rawHex}) .

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

The -l causes a line feed to be added to the output so you don't need to use echo . Feel free to remove the l if you're not actually using echo

Generating code (as suggested in the earlier answer) is a horrible practice.

A working solution is

rawHex=0x41000000
echo $(perl -e "print unpack 'f', pack 'L', ${rawHex}")

Your code has two problems. The first is that in bash, variables between single quotes ' will not be evaluated. That's why I inverted single and double quotes in your example.

The second problem is the use of ENV . I am not sure why you use it, but you don't need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM