How to write binary data in Bash

前端 未结 6 2166
后悔当初
后悔当初 2021-01-20 05:54

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 w

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-20 06:43

    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.

提交回复
热议问题