Skip to content

Instantly share code, notes, and snippets.

@c02y
Last active May 10, 2018 08:01
Show Gist options
  • Save c02y/953ac1aa4ed7d59457b33718f79aafbf to your computer and use it in GitHub Desktop.
Save c02y/953ac1aa4ed7d59457b33718f79aafbf to your computer and use it in GitHub Desktop.
bit operations of two numbers
#!/bin/bash
usage()
{
echo "bit operations of two numbers"
echo
echo "Usage: $(basename $0) NUM1 OPS NUM2 [d]"
echo "OPS: a(&, and), o(|, or), x(^, xor), l(<<, left), r(>>, right)"
echo "d means result will be dec, default is hex"
exit
}
if [ "$#" -lt 3 ] || [ "$#" -gt 4 ] || [[ "$2" != [aoxlr] ]]; then
usage
fi
if [ "$4" = "d" ]; then
echo -n "dec: "
if [ "$2" = "a" ]; then
printf '%d\n' "$(( $1 & $3 ))"
elif [ "$2" = "o" ]; then
printf '%d\n' "$(( $1 | $3 ))"
elif [ "$2" = "x" ]; then
printf '%d\n' "$(( $1 ^ $3 ))"
elif [ "$2" = "l" ]; then
printf '%d\n' "$(( $1 << $3 ))"
elif [ "$2" = "r" ]; then
printf '%d\n' "$(( $1 >> $3 ))"
fi
elif [ "$4" = "" ]; then
echo -n "hex: "
if [ "$2" = "a" ]; then
printf '%X\n' "$(( $1 & $3 ))"
elif [ "$2" = "o" ]; then
printf '%X\n' "$(( $1 | $3 ))"
elif [ "$2" = "x" ]; then
printf '%X\n' "$(( $1 ^ $3 ))"
elif [ "$2" = "l" ]; then
printf '%X\n' "$(( $1 << $3 ))"
elif [ "$2" = "r" ]; then
printf '%X\n' "$(( $1 >> $3 ))"
fi
else
usage
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment