Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
You need to specify the endian-ness. –  richard Aug 8 at 9:45

2 Answers 2

up vote 5 down vote accepted
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
share|improve this answer
    
With l, in my 64-bit machine: perl -MConfig -e 'print $Config{longsize}' , result is 8. –  cuonglm Aug 8 at 9:56
2  
@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 –  Stéphane Chazelas Aug 8 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.

share|improve this answer
    
i is not guaranteed to be 4-byte wide. l is –  Stéphane Chazelas Aug 8 at 9:41
    
@StéphaneChazelas: Yes, add note in my answer. –  cuonglm Aug 8 at 10:33
    
The -l option adds unwanted 0x0a bytes to the output. –  Stéphane Chazelas Aug 8 at 11:41
    
@StéphaneChazelas you are using a Unicode locale. –  hildred Aug 8 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. –  Stéphane Chazelas Aug 8 at 16:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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