Jen*_*sen 6 bash shell bit-manipulation bitmask
在shell脚本中是否可以使用以下代码?
var1=0xA (0b1010)
if ( (var1 & 0x3) == 0x2 ){
...perform action...
}
Run Code Online (Sandbox Code Playgroud)
只是为了让我的意图100%清除我想要的动作是检查var1在0x3(0b0011)的位并确保它等于0x2(0b0010)
0b1010
&0b0011
_______
0b0010 == 0x2 (0b0010)
Run Code Online (Sandbox Code Playgroud)
POSIX 算术表达式支持位操作:
if [ $(( var1 & 0x3 )) -eq $(( 0x2 )) ]; then
Run Code Online (Sandbox Code Playgroud)
但是,在 中使用算术语句要简单一些bash
:
if (( (var1 & 0x3) == 0x2 )); then
Run Code Online (Sandbox Code Playgroud)