18

Possible Duplicate:
using bash: write bit representation of integer to file

I need to write the size of a file into a binary file. For example:

$ stat -c %s in.txt 
68187

$ stat -c %s in.txt >> out.bin

Instead of writing 68187 as a string to out.bin, i want to write it as a 4 bytes integer to out.bin.

1
  • it looks like a duplicate, but none of the answers there really solve this problem. Mar 31, 2012 at 11:16

3 Answers 3

39

This is what I could come up with:

int=65534
printf "0: %.8x" $int | xxd -r -g0 >>file

Now depending on endianness you might want to swap the byte order:

printf "0: %.8x" $int | sed -E 's/0: (..)(..)(..)(..)/0: \4\3\2\1/' | xxd -r -g0 >>file

Example (decoded, so it's visible):

printf "0: %.8x" 65534 | sed -E 's/0: (..)(..)(..)(..)/0: \4\3\2\1/' | xxd -r -g0 | xxd
0000000: feff 0000                                ....

This is for unsigned int, if the int is signed and the value is negative you have to compute the two's complement. Simple math.

6
  • Had never seen xxd. And here I really thought there was finally something a little chain of commands couldn't do.... :) (Edit: I feel like I should state that I did not down vote you. Just figured I should say since it appeared right when I commented)
    – Corbin
    Mar 31, 2012 at 10:47
  • it didn't cross my mind it was you, but oooh maaan, who downvoted this? :/ Mar 31, 2012 at 10:51
  • I'd be quite curious to know. I may be paranoid, but I swear lately people have gotten very down vote happy on perfectly fine answers.
    – Corbin
    Mar 31, 2012 at 10:52
  • +1 In ubuntu: printf "%.8x" 65534 | xxd -r -p
    – kev
    Mar 31, 2012 at 11:06
  • great! a minor issue, the sed ... should be: sed -e 's/0\: \(..\)\(..\)\(..\)\(..\)/0\: \4\3\2\1/' thanks a lot!
    – Dagang
    Mar 31, 2012 at 15:01
4

You can use the following function to convert a numeric VALUE into its corresponding character:

chr() {
  printf \\$(printf '%03o' $1)
}

You have to convert the byte values individually, after each other in the correct order (endianess) for the machine/architecture that you use. So I guess, a little use of another scripting language that supports binary output would do the job best.

2

See if this works for you

perl -e "print pack('L',`stat -c %s in.txt`)">>out.bin 
1

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