Bitwise Operators & Binary Numbers
Video
JavaScript Notes
JavaScript
// bitwise.js
// JavaScript Bitwise operators
// AND &
// OR |
// XOR ^
// NOT ~
// Shift left <<
// Shift right >>
let log = console.log;
let n = 10; // 1010
let i = 6; // 110
log(n.toString(2), i.toString(2)); // returning at base 2
log( "AND & ", (n & i) ); // returns 0010 (or 2)
log( "OR | ", (n | i) ); // returns 1110 (or 14)
log( "XOR ^ ", (n ^ i) ); // returns 1100 (or 12) - XOR = exclusive OR
// ~ 1010
// 0101
// x = - (x+1)
log( "NOT ~ ", (~n) ); // returns - 11
//PERMISSIONS
// read, write, delete
let perm = 6;
let allowedToRead = (perm & 4 == 4)? true:false;
let allowedToWrite = (perm & 2 == 2)? true:false;
let allowedToDelete = (perm & 1 == 1)? true:false;
// ODD or EVEN
for (var c=0; c<50; c++){
if(c & 1){
// odd
} else {
// even
}
}
// SHIFTING TO THE LEFT or RIGHT
// 101010 >> 4 = 10 (or 2)
// 111 >> 1 = 11 (or 3)
log( 7 >> 1); // returns 3
// 111 << 1 = 1110 (or 14) - shifting 1 to the left is the same as multiplying the number by two.
// HEXADECIMAL COLORS
// FF3300 - 24 bit values: 8 bits RED, 8 bits GREEN 8 bits BLUE
// GREEN – Shift 8 >>, AND 11111111 (255)
// 111111110011001100000000 >> 8 = 1111111100110011
// 1111111100110011
// 0000000011111111
// 00110011
var color = 0xFF3300; // Hexadecimals in JavaScript start with 0x
var noblue = color >> 8;
var green = noblue & 255;
log('GREEN', green, green.toString(16)) // returns: GREEN, 51, 33
/************************************* counting in decimal, binary
0 0
1 1 2^0
2 10 2^1
3 11
4 100 2^2
5 101
6 110
7 111
8 1000 2^3
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111
16 11111 2^4
************************************/
Feedback
Submit and view feedback