Manoj
Manoj

Reputation: 51

I need a XOR output with two binary numbers as input in shell script

I am trying to perform a XOR bitwise operation with two binary numbers in shell. If, a=00001000 b=00110011 My output should be 00111011

Does Shell supports XOR operation for binary numbers? I have also tried by downloading the logic.bc file from http://phodd.net/gnu-bc/code/logic.bc but it shows the error Runtime error (func=(main), adr=270): Function xor not defined. Can anyone help me with the solution

Upvotes: 1

Views: 582

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207660

Updated Answer

Your numbers seem to be strings of binary digits, so you would need to convert those:

perl -e 'print (oct("0b".$ARGV[0])^oct("0b".$ARGV[1]))' 00111100 00001101
49

Or, if you want the answer in the same format:

perl -e 'printf("%.8b",oct("0b".$ARGV[0])^oct("0b".$ARGV[1]))' 00111100 00001101
00110001

Original Answer

Rather than introduce a dependency on downloading an obscure bc script, maybe consider leveraging something that is already built-in.

For example, Perl is built-in on Linux and macOS:

perl -e 'print ((0+$ARGV[0])^$ARGV[1])' 60 13
49

Likewise PHP:

php -r 'echo (0+$argv[1])^$argv[2];' 60 13
49

You may have awk:

awk -v x=60 -v y=13 'BEGIN{print xor(x,y)}'
49

Or Python:

python -c 'import sys; print(int(sys.argv[1])^int(sys.argv[2]))' 60 13
49

Upvotes: 2

Related Questions