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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9955020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:31:41  来源:igfitidea点击:

How to write integer to binary file using Bash?

linuxbashshell

提问by Dagang

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

可能的重复:
使用 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

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

我想将 168187 的 4 字节 int 表示写入 out.bin,而不是将“68187”字符串写入 out.bin。

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

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

采纳答案by Karoly Horvath

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: /' | xxd -r -g0 >>file

Example (decoded, so it's visible):

示例(已解码,因此可见):

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

This is for unsignedint, if the int is signed andthe value is negativeyou have to compute the two's complement. Simple math.

这是针对无符号整数,如果整数是有符号的并且值为,则必须计算二进制补码。简单的数学。

回答by Hannes

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

您可以使用以下函数将数值 VALUE 转换为其相应的字符:

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

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.

您必须按照您使用的机器/架构的正确顺序(字节序)逐个转换字节值。所以我想,稍微使用另一种支持二进制输出的脚本语言会做得最好。

回答by pizza

See if this works for you

看看这是否适合你

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