File Conversion – Convert ASCII Integers to Binary File

binaryconversionfilestext processingUtilities

I have a file that contains a long list of integers written in ascii separated with newlines, like such:

-175
2
-19345
345592
-45
2355

etc…

I want to convert this file into a "binary" file containing the same integers, written as actual 4 byte integers.

What command-line tool can I use to achieve this?

Best Answer

perl -pe '$_=pack"l",$_' < infile > outfile

Uses the local endianness. Use l> instead of l for big-endian, and l< for little-endian.

See perldoc -f pack for more info.

Note that it's l as in lowercase L (for long integer), not the 1 digit.

$ printf '%s\n' 1234 -2 | perl -pe '$_=pack"l",$_'| od -vtd4
0000000        1234          -2
0000010
$ printf '%s\n' 1234 -2 | perl -pe '$_=pack"l>",$_'| od -vtx1
0000000 00 00 04 d2 ff ff ff fe
0000010
Related Question