using bash: write bit representation of integer to file

前端 未结 9 941
春和景丽
春和景丽 2020-12-15 20:30

I have a file with binary data and I need to replace a few bytes in a certain position. I\'ve come up with the following to direct bash to the offset and show me that it fou

9条回答
  •  盖世英雄少女心
    2020-12-15 20:57

    printf is more portable than echo. This function takes a decimal integer and outputs a byte with that value:

    echobyte () {
        if (( $1 >= 0 && $1 <= 255 ))
        then
            printf "\\x$(printf "%x" $1)"
        else
            printf "Invalid value\n" >&2
            return 1
        fi
    }
    
    $ echobyte 97
    a
    $ for i in {0..15}; do echobyte $i; done | hd
    00000000  00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f  |................|
    00000010
    

提交回复
热议问题