t.data中有一个字节0x1
我该如何读取该文件执行位数学对它的内容在POSIX shell?
echo $((1 << 1))
给出2,但是
echo $(($((cat t.data)) << 1))
和var d=$(< t.data); echo $(("$d" << 1))
失败。
POSIX sh和Bash不适合处理二进制数据,但是您可以使用printf
在字节和整数之间来回转换:
# Read the ascii value of the first byte
num=$(printf "%d" "'$(head -c 1 < t.data)")
echo "The decimal representation of the first byte is $num"
# Do some math on it
num=$(( (num << 1) & 0xFF ))
echo "After shifting by one, it became $num"
# Write back the result via an octal escape
oct=$(printf '%03o' "$num")
printf "\$oct" > t.data