本文介绍了如何使用Bash将整数写入二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将文件的大小写入二进制文件.例如:
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.
这篇关于如何使用Bash将整数写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!