天天看點

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.