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



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?

  • You need to specify the endian-ness. Aug 8 '14 at 9:45
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
$ printf '%s\n' 1234 -2 | perl -pe '$_=pack"l>",$_'| od -vtx1
0000000 00 00 04 d2 ff ff ff fe
  • With l, in my 64-bit machine: perl -MConfig -e 'print $Config{longsize}' , result is 8.
    – cuonglm
    Aug 8 '14 at 9:56
  • 3
    @Gnouc, Yes l is etymologically for long integer from the time where longs where 32bit wide. l has stayed and is guaranteed to stay 32bit wide even on systems where longs are wider (so l no longer means long in practice). Use l! if you want your system/compiler's longs Aug 8 '14 at 9:59

Another perl:

$ perl -pe '$_ = pack("i", $_)' file

i represents signed integer value (which is represent at least 4 bytes, depend on local C compiler). Use l option like @Stéphane Chazelas's answer for always use 32-bit.

  • i is not guaranteed to be 4-byte wide. l is Aug 8 '14 at 9:41
  • @StéphaneChazelas: Yes, add note in my answer.
    – cuonglm
    Aug 8 '14 at 10:33
  • The -l option adds unwanted 0x0a bytes to the output. Aug 8 '14 at 11:41
  • @StéphaneChazelas you are using a Unicode locale.
    – hildred
    Aug 8 '14 at 16:25
  • @hildred, yes, as a matter of fact, I am, but the 0x0as are the newline characters added by -l regardless of the locale. Aug 8 '14 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.