天天看点

bash 将二进制转换为十进制,如何在Bash中写入二进制数据

bash 将二进制转换为十进制,如何在Bash中写入二进制数据

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))"

which of course can be nested in the above:

binary=00000011

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

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.