如何使用Bash将整数写入二进制文件?

如何使用Bash将整数写入二进制文件?

问题描述:

可能重复:
使用bash:将整数的位表示形式写入文件

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

我不是将"68187"字符串写入out.bin,而是要将168187的4个字节的int表示形式写入out.bin.

Instead of writing "68187" string to out.bin, i want to write the 4 bytes int representation of 168187 to out.bin.

如何将"68187"转换为4个字节的整数?

How can i convert "68187" to 4 bytes int?

这是我能想到的:

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                                ....

这是针对 unsigned int的,如果int是 signed并且的值是 negative ,则必须计算两者的补数.简单的数学.

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.