如何在Bash中写入二进制数据 [英] How to write binary data in Bash

查看:704
本文介绍了如何在Bash中写入二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说bash脚本中有一个值为"001"的变量,我该如何将该二进制数据写入文件中,作为位(作为"001"而不是"1"),echo将其写入字符串,但是我想写入

Let us say there is a variable in bash script with value "001" how can i write this binary data into a file as bits (as "001" not "1") echo writes it as string but i want to write in bits.

推荐答案

您可以使用以下命令以十六进制或八进制形式写入任意字节:

You can write arbitrary bytes in hex or octal with:

printf '\x03' > file   # Hex
printf '\003' > file   # Octal

如果您使用的是二进制文件,则有点麻烦,但是您可以使用以下命令将其转换为八进制:

If you have binary, it's a bit tricker, but you can turn it into octal with:

printf '%o\n' "$((2#00000011))"

当然可以嵌套在上面:

binary=00000011
printf "\\$(printf '%o' "$((2#$binary))")" > file

请注意,这最多只能使用8位.如果要写入更长的值,则必须将其分成8组.

Note that this only works with up to 8 bits. If you want to write longer values, you have to split it up into groups of 8.

这篇关于如何在Bash中写入二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆