whiteWolf whiteWolf -4 years ago 137
Perl Question

Convert sequence of decimal numbers to Big endian float

I have an external software that uses images stored as long sequences of 4-byte floats, as Big Endian, no header. I can create a small example image using

, and hence I can control possible separators, or output my (float) number sequence as e.g. hex or decimal values. However, I have not found a way to write it to file as 4-byte floats. Hence I try to use Perl's pack to convert my sequence of decimal base10 numbers to 4-byte floats, Big Endian, which works for a single value, but my Perl experience is too limited to get it to work for a sequence of values.

Could someone more proficient in Perl help me out? To look at the output bit sequence, I pipe it to the command
xxd -b

perl -e "print pack('f>*',3)"|xxd -b # outputs decimal 3 (base10) on the wanted format:
# 01000000 01000000 00000000 00000000

perl -e "print pack('f>*',3,7,8)"|xxd -b # outputs the requested dummy sequence correctly
# 01000000 01000000 00000000 00000000 01000000 11100000
# 00000000 00000000 01000001 00000000 00000000 00000000

echo 1|awk 'BEGIN{printf("%d,%d,%d",3,7,8);}'|xxd -b # creates same dummy sequence, in awk - here separated by ,

echo 1|awk 'BEGIN{printf("%d,%d,%d",3,7,8);}'|perl -e "print pack('f>*',<STDIN>)"|xxd -b
# outputs correct conversion of 3, but seems to ignore 7 and 8
# 01000000 01000000 00000000 00000000

I guess the separator has to be handled differently? I also tried this form of the Perl part

perl -ne 'print pack "f>*",$_'

Any help is appreciated.

Answer Source




split(/,/, <STDIN>)

Also, it's probably best if you wrap the Perl program in single-quotes. No difference here, but it's a good habit.

perl -e'print pack "f>*", split /,/, <STDIN>'

Cleanly handles the newline (if there is one):

perl -ne'chomp; print pack "f>*", split /,/'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download