Bash 对cat的输出进行数学运算

Bash 对cat的输出进行数学运算,bash,shell,bit-manipulation,cat,Bash,Shell,Bit Manipulation,Cat,我在t.data中有一个单字节0x1 在POSIX shell中,如何读取该文件以对其内容执行位运算 echo$1POSIX sh和Bash不适合处理二进制数据,但您可以使用printf在字节和整数之间来回转换: # Read the ascii value of the first byte num=$(printf "%d" "'$(head -c 1 < t.data)") echo "The decimal representati

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

在POSIX shell中,如何读取该文件以对其内容执行位运算


echo$1POSIX 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
 

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
 

谢谢为什么第二行的撇号是必要的?还有,为什么cat在这里不起作用?因为这就是如何将字符转换为ASCII值的方法。看到男人猛击下了吗printf@Christiansh/bash中的所有数字都是数字ascii字符串。字节0x01是控制字符,不是有效的ASCII整数。有关将字符值转换为十进制和十六进制的详细信息,请参阅。谢谢。为什么第二行的撇号是必要的?还有,为什么cat在这里不起作用?因为这就是如何将字符转换为ASCII值的方法。看到男人猛击下了吗printf@Christiansh/bash中的所有数字都是数字ascii字符串。字节0x01是控制字符,不是有效的ASCII整数。有关将字符值转换为十进制和十六进制的详细信息,请参阅。