19

Unfortunately bc and calc don't support xor.

4 Answers 4

41

Like this:

echo $(( 0xA ^ 0xF ))

Or if you want the answer in hex:

printf '0x%X\n' $(( 0xA ^ 0xF ))

On a side note, calc(1) does support xor as a function:

$ calc
base(16)
    0xa
xor(0x22, 0x33)
    0x11
1
  • 1
    In case your numbers are binary: printf '0x%X\n' $(( 2#1010 ^ 2#1111 )) Commented Feb 10, 2022 at 16:50
23

With any POSIX shell:

$ printf '%#x\n' "$((0x11 ^ 0x22))"
0x33
2
  • %#x works in C too, nice!
    – Zombo
    Commented Jun 27, 2016 at 22:54
  • 2
    @StevenPenny, note that one difference with 0x%x is that it gives 0 instead of 0x0 for 0. Commented Jul 27, 2020 at 11:36
14

gdb has powerful expression calculator:

gdb -q -ex 'print/x 0xA ^ 0xF' -ex q

A shell function:

calc_gdb() { gdb -q -ex "print/x $*" -ex q;}
calc_gdb 0xA ^ 0xF

$1 = 0x5
2
  • 4
    Amusing, but it seems like a sledgehammer to crack a nut!
    – abligh
    Commented Jun 28, 2016 at 8:16
  • 1
    Useful for the more general case of evaluating expressions, but not for XOR Commented Jun 28, 2016 at 8:57
7

It is possible to do that in bc:

echo 'xor(10,15)' | bc -l logic.bc

Or in hex:

echo 'obase=16;ibase=16; xor(AA,FF)' | bc -l logic.bc

Using the logic file from here.

Just do wget http://phodd.net/gnu-bc/code/logic.bc to get it.

4
  • Wow, that site is the bc(1) geek's heaven. :) Thank you for the link. Commented Jun 28, 2016 at 17:24
  • My version of "bc" doesn't seem to have the XOR function and just says: Runtime error (func=(main), adr=51): Function xor not defined.
    – slacy
    Commented Oct 5, 2016 at 21:13
  • @slacy did you get the logic.bc file referenced there? That is what defines xor it seems Commented Oct 11, 2016 at 17:53
  • The functions in phodd.net/gnu-bc/code/logic.bc do work with GNU bc but do not work with macOS bc (bc 4.0.2, Gavin D. Howard and contributors) . The problem is in the precedence between boolean NOT (!) and Modulus (%). ! has the precedence in macOS bc but in GNU bc % has the precedence over !.
    – diciotto
    Commented Jan 28 at 0:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .