A Real Life Application for Bit Math

function doesContainItem(list, item) {
for testItem in list {
if (testItem == item) {
return true
}
}
return false
}
00000000000000000000000000000011 // integer 3
00000001  // 8-bit integer 1
00000010 // 8-bit integer 2
00000011 // 8-bit integer 3
00000100 // 8-bit integer 4
00000101 // 8-bit integer 5
00001000 // 8-bit integer 8
00010000 // 8-bit integer 16
const black = 1    // 00000001 in memory
const red = 2 // 00000010 in memory
const orange = 4 // 00000100 in memory
const yellow = 8 // 00001000 in memory
const green = 16 // 00010000 in memory
const indigo = 32 // 00100000 in memory
const violet = 64 // 10000000 in memory
const blackWithRed = black|red // bit OR operation00000001 // black memory value
00000010 // red memory value
-------- // bit OR operation
00000011 // blackWithRed memory value
const myVariable = 3 & 100000011 // integer 3 memory value
00000001 // integer 1 memory value
-------- // bit AND operation
00000001 // myVariable memory value
const rainbow = [ red, orange, yellow, green, indigo, violet ]
// O(n) complexity
function isPartOfRainbow (rainbow, color) {
return doesContainItem(rainbow, color)
}
// O(n) complexity
const rainbowBitMask = red|orange|yellow|green|blue|indigo|violet
// bit AND operation
// O(n) complexity
function isPartOfBitMaskRainbow(rainbowBitMask, color) {
const maskBitAndColor = rainbowBitMask & color // bit AND operation
return maskBitAndColor > 0
}
// O(1) complexity
const rainbowBitMask = red|orange|yellow|green|blue|indigo|violet
// O(n) complexity
00000010 // red memory value
00000100 // orange memory value
00001000 // yellow memory value
00010000 // green memory value
00100000 // blue memory value
01000000 // indigo memory value
10000000 // violet memory value
--------
11111110 // rainbowBitMask
const isPartOfRainbow = isPartOfBitMaskRainbow(rainbowBitMask, orange)function isPartOfBitMaskRainbow(rainbowBitMask, color) {
const maskBitAndColor = rainbowBitMask & color

11111110 // rainbowBitMask
00000100 // orange
-------- // bit AND operation
00000100 // maskBitAndColor memory value is now equal to integer 8

return maskBitAndColor > 0
// 8 > 0 is true
}
// O(1) complexity

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Drake Evans

Drake Evans

A smart man can rationalize anything; set rules and don't break them. Biomedical Engineering, Computer Science, Finance, Economics.