bash - 对 cat 的输出做数学运算
问题描述
我在 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
推荐阅读
- c# - VS2019:加载解决方案文件,每次都不能正确加载WPF项目
- http - 如何发送分块传输编码的超响应?
- javascript - 使用 jQuery click() 处理程序
- database - Oracle v$session,v$mystat 给出错误:表或视图在选择时不存在
- laravel - 分页有问题,数据消失
- git - IntelliJ 快速切换到多个 Git 分支
- firebase - E/MethodChannel#plugins.flutter.io/firebase_auth(16707):java.lang.IllegalArgumentException:给定字符串为空或为空
- reactjs - 如何自定义 antd tab 活动底部标签栏颜色
- python - 如何让 ipywidgets 交互以在 HTML 中工作?
- python - Python:Nessus API 未下载报告