How to write binary data in Bash

前端 未结 6 2051
后悔当初
后悔当初 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:45

    Most often you want to write a pattern (for instance a 32 bit pattern).

    # Write 32 bits 5 times to a file 
    for i in {1..5}
    do
       printf '\x12\x34\xAC\xCD' >> binaryfile.bin
    done
    

    Another example:

    for i in {1..255}
    do
        hx=$( printf "%x" $i )
        output="\x$hx\x00\x00\x00"
        printf "%b" $output >> binaryfile.bin 
    done
    

提交回复
热议问题