What does ampersand mean in arithmetic evaluation and numbers with x in Bash?

I wonder what makes the following comparison as far as possible, particularly with respect to the symbols 0x2and &and what they are doing,

if [ $((${nValid} & 0x1)) -eq 1 ]; then
  #...snip...
fi

if [ $((${nValid} & 0x2)) -eq 2 ]; then
  #...snip...
fi
+3
source share
5 answers

Bit-based nValid testing.

The bitwise operator AND( &) means a bitwise number, the operator performs a comparison AND. So, if nValid is a byte (8-bit) value, then look at the operation in binary format:

nValue & 0b00000001

If nValue is 42, the operation will look like this:

(nValue = 0b00101010) & 0b00000001 => 0b00000000 // (does not have the last bit set)
(nValue & 0b00000001) == 0b00000001 // false

and for the second ( nValid & 0x2)

(nValue = 0b00101010) & 0b00000010 => 0b00000010 // (has the 2nd-to-last bit set)
(nValue & 0b00000010) == 0b00000010 // true

; AND OR .

0b00001000 | 0b00000010 | 0b00000001 => 0b00001011
+2

& . , 0x1 , ${nVAlid}.

.

+3

script ( 10), . , 0, ( 8). , 0x, ( 16). # BASE # NUMBER ( ).

, [ $((${nValid} & 0x1)) -eq 1 ], $nValid 0x1 1. .

,

+3

0x1 0x2 - 1 2. & - . , nValid, (0x1) (0x2).

( C):

if (val & (1 << bitNumber) == (1 << bitNumber)) {
  // The bit at position bitNumber (from least to most significant digit) is set
}

<< - -. 1 << 0 == 1, 1 << 1 == 2, 1 << 2 == 4,...

:

if [ $((${nValid} & X)) -eq X ]; then

X - 2 ( , ).

+2

:

if (( nValid & 2#00000001 )); then
  #...snip...
fi

if (( nValid & 2#00000010 )); then
  #...snip...
fi

, . , *. , . .

, :

declare -r FOO=$((2#00000001))
declare -r BAR=$((2#00000010))
if (( nValid & FOO )); then
  #...snip...
fi
if (( nValid & BAR )); then
  #...snip...
fi

* , :

if (( (nValid & (FOO | BAR)) == (FOO | BAR) )); then
  #...snip...
fi

, == , .

Bash:

(( var |= FOO ))    # set the bits in FOO into var
(( var &= ~BAR ))   # clear the bits in BAR from var
+2

Source: https://habr.com/ru/post/1760133/


All Articles