How to write binary data in Bash

前端 未结 6 2046
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2021-01-20 06:49

    I needed this recently, someone might find it useful :

    #!/bin/bash
    
    # generate bitmasks for a C array
    
    # loop counter
    NUMBER=0
    MAX_BITMASK_LENGTH=8
    # max loop value : 2^8 = 255
    MAXVAL=$((2**MAX_BITMASK_LENGTH))
    # line number
    LINE=0
    
    # echo start of C array
    echo "    const long int bitmasks[${MAX_BITMASK_LENGTH}] = {"
    
    # loop over range of values
    while [ ${NUMBER} -le ${MAXVAL} ] ; do
    
        # use bc to convert to binary
        BINARY=`echo -e "obase=2\n${NUMBER}"| bc`
    
        # print current number, linenumber, binary
        printf "%12s, /* (%i) %8s */\n" ${NUMBER} ${LINE} ${BINARY}
    
        # increase loop value to next value
        NUMBER=$(((NUMBER*2)+1))
    
        # increment line number
        LINE=$((LINE+1))
    done
    
    # echo end of C array
    echo "        };"
    

    This outputs:

    $ ./generate_bitmasks.sh
        const long int bitmasks[8] = {
               0, /* (0)        0 */
               1, /* (1)        1 */
               3, /* (2)       11 */
               7, /* (3)      111 */
              15, /* (4)     1111 */
              31, /* (5)    11111 */
              63, /* (6)   111111 */
             127, /* (7)  1111111 */
             255, /* (8) 11111111 */
            };
    

提交回复
热议问题