Lubos Rendek

The only solution is determination.

BASH Bitwise XOR Example

| Comments

Normally, I get around with basic logical operators like AND or OR. However, today I needed XOR to make my script more compact and shorter. Here is a short example on how to use XOR ( bitwise exclusive OR ) in BASH:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash

# bitwise exclusive OR ( XOR ) example
echo XOR Truth table:

echo 0XOR0=$(( 0 ^ 0 ))
echo 0XOR1=$(( 0 ^ 1 ))
echo 1XOR0=$(( 1 ^ 0 ))
echo 1XOR1=$(( 1 ^ 1 ))

echo Conditional XOR function example

function xor {
        if (( $1 ^ $2 )) ;then
                echo 1
        else
                echo 0
        fi
}

echo -n 0XOR0= 
xor 0 0
echo -n 0XOR1=
xor 0 1
echo -n 1XOR0=
xor 1 0
echo -n 1XOR1=
xor 1 1

Bash Script execution and output:

1
2
3
4
5
6
7
8
9
10
11
$ bash xor.sh 
XOR Truth table:
0XOR0=0
0XOR1=1
1XOR0=1
1XOR1=0
Conditional XOR function example
0XOR0=0
0XOR1=1
1XOR0=1
1XOR1=0

Comments