Programming Challenge: Implementing bitwise operators.

Emerald_Knight
2018-06-16T07:06:22Z

Background: Bitwise operators are operators that perform conditional operations at the binary level. These operators are bitwise AND &, bitwise OR |, bitwise XOR ^, and bitwise NOT ~, not to be confused with their logical operator counterparts, i.e. &&, ||, !=, and ! respectively.

Specifically, these operations take the binary values of the left- and right-hand terms and perform the conditional operation on each matching bit position between both values.

For instance, 3 | 4 takes the binary value 010 from 2 and 100 from 4. From left to right, we compare 0 || 1, 1 || 0, and 0 || 0 to get 110 as the resulting binary. This produces the integer value 6.

Goal: Your challenge is to implement one or more of these bitwise operators without using the native operators provided to you by your language of choice. Logical operators are allowed, however. These operators should work on integer values. These operators will likely take on the form of a function or method that accepts two arguments.

Bonus challenges:

Implement all of the operators.

Don't use any native binary conversion utilities.

Whether or not you implement all operators, write your code in such a way that allows for good code reusability.

For statically typed languages, handle integers of different types (e.g. int vs. uint).

Edit: Minor correction for the sake of accuracy, courtesy of @teaearlgraycold.

Comments URL: https://tildes.net/~comp/2cg/programming_challenge_implementing_bitwise_operators

Votes: 12

Comments: 22