
Basic Data Operation

This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:


Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses




Task

Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.

All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.

If any operation is not available in your language, note it.




 
PROGRAM "bitwise"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION ULONG Rotr(ULONG x, ULONG s)
 
FUNCTION Entry()
  SLONG a, b
  ULONG ua, ub
  a = 21
  b = 3
  ua = a
  ub = b
  PRINT
  PRINT "= Decimal ="
  PRINT LTRIM$(STR$(a)); " AND"; b; ":"; a & b ' also: a AND b
  PRINT LTRIM$(STR$(a)); " OR"; b; ":"; a | b ' also: a OR b
  PRINT LTRIM$(STR$(a)); " XOR"; b; ":"; a ^ b' also: a XOR b
  PRINT "NOT"; a; ":"; ~a ' also: NOT a
  PRINT LTRIM$(STR$(a)); " <<<"; b; ":"; a <<< b ' arithmetic left shift
  PRINT LTRIM$(STR$(a)); " >>>"; b; ":"; a >>> b ' arithmetic right shift
  PRINT LTRIM$(STR$(ua)); " <<"; b; ":"; ua << b ' bitwise left shift
  PRINT LTRIM$(STR$(ua)); " >>"; b; ":"; ua >> b ' bitwise right shift
  PRINT LTRIM$(STR$(ua)); " rotr"; ub; ":"; Rotr(ua, ub)
  PRINT
  PRINT "= Binary ="
  PRINT BIN$(a); " AND "; BIN$(b); ": "; BIN$(a & b)
  PRINT BIN$(a); " OR "; BIN$(b); ": "; BIN$(a | b)
  PRINT BIN$(a); " XOR "; BIN$(b); ": "; BIN$(a ^ b)
  PRINT "NOT "; BIN$(a); ": "; BIN$(~a)
  PRINT BIN$(a); " <<< "; BIN$(b); ": "; BIN$(a <<< b)
  PRINT BIN$(a); " >>> "; BIN$(b); ": "; BIN$(a >>> b)
  PRINT BIN$(ua); " << "; BIN$(b); ": "; BIN$(ua << b)
  PRINT BIN$(ua); " >> "; BIN$(b); ": "; BIN$(ua >> b)
  PRINT BIN$(ua); " Rotr "; BIN$(ub); ": "; BIN$(Rotr(ua, ub))
END FUNCTION
 
' Rotate x to the right by s bits
FUNCTION ULONG Rotr(ULONG x, ULONG s)
  RETURN (x >> s) | (x << (SIZE(ULONG) * 8 - s))
END FUNCTION
END PROGRAM
 