首页 > 解决方案 > 对 cat 的输出做数学运算

问题描述

我在 t.data 中有一个字节 0x1。

我将如何读取该文件以对其在 POSIX shell 中的内容执行按位数学运算?

echo $((1 << 1))

给出 2,但是

echo $(($((cat t.data)) << 1))

var d=$(< t.data); echo $(("$d" << 1))

失败。

标签: bashshellbit-manipulationcat

解决方案


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
 

推荐阅读