javascript

examples

examples.js
/**
 * ============================================
 * 3.5 BITWISE OPERATORS - EXAMPLES
 * ============================================
 */

// ============================================
// EXAMPLE 1: Binary Representation
// ============================================

console.log('--- Binary Representation ---');

// Convert decimal to binary string
console.log('13 in binary:', (13).toString(2)); // "1101"
console.log('255 in binary:', (255).toString(2)); // "11111111"

// Binary literals (ES6)
const binary = 0b1101;
console.log('0b1101 =', binary); // 13

// Parse binary string to number
console.log("Binary '1101' =", parseInt('1101', 2)); // 13

// Hexadecimal
console.log('0xFF =', 0xff); // 255

// ============================================
// EXAMPLE 2: Bitwise AND (&)
// ============================================

console.log('\n--- Bitwise AND (&) ---');

console.log('12 & 5 =', 12 & 5); // 4
console.log('  12 = ' + (12).toString(2).padStart(4, '0'));
console.log('   5 = ' + (5).toString(2).padStart(4, '0'));
console.log('   4 = ' + (4).toString(2).padStart(4, '0'));

// Check if even (last bit is 0)
const isEven = (n) => (n & 1) === 0;
console.log('isEven(4):', isEven(4)); // true
console.log('isEven(7):', isEven(7)); // false

// Masking - extract low 4 bits
const num = 0b11011010; // 218
const low4 = num & 0b1111; // 0b1010 = 10
console.log('Low 4 bits of', num, ':', low4);

// ============================================
// EXAMPLE 3: Bitwise OR (|)
// ============================================

console.log('\n--- Bitwise OR (|) ---');

console.log('12 | 5 =', 12 | 5); // 13
console.log('  12 = ' + (12).toString(2).padStart(4, '0'));
console.log('   5 = ' + (5).toString(2).padStart(4, '0'));
console.log('  13 = ' + (13).toString(2).padStart(4, '0'));

// Set a specific bit
const setBit = (n, pos) => n | (1 << pos);
console.log('Set bit 2 in 5:', setBit(5, 2)); // 5 | 4 = 7 (0101 | 0100 = 0111)

// Floor positive numbers (faster than Math.floor)
console.log('3.7 | 0 =', 3.7 | 0); // 3
console.log('9.99 | 0 =', 9.99 | 0); // 9

// ============================================
// EXAMPLE 4: Bitwise XOR (^)
// ============================================

console.log('\n--- Bitwise XOR (^) ---');

console.log('12 ^ 5 =', 12 ^ 5); // 9
console.log('  12 = ' + (12).toString(2).padStart(4, '0'));
console.log('   5 = ' + (5).toString(2).padStart(4, '0'));
console.log('   9 = ' + (9).toString(2).padStart(4, '0'));

// XOR properties
console.log('5 ^ 5 =', 5 ^ 5); // 0 (self-inverse)
console.log('5 ^ 0 =', 5 ^ 0); // 5 (identity)

// Swap without temp variable
let a = 10,
  b = 20;
console.log('Before swap: a =', a, ', b =', b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log('After swap: a =', a, ', b =', b);

// Toggle bit
const toggleBit = (n, pos) => n ^ (1 << pos);
console.log('Toggle bit 1 in 5:', toggleBit(5, 1)); // 5 ^ 2 = 7

// ============================================
// EXAMPLE 5: Bitwise NOT (~)
// ============================================

console.log('\n--- Bitwise NOT (~) ---');

console.log('~5 =', ~5); // -6
console.log('~-3 =', ~-3); // 2
console.log('~0 =', ~0); // -1
console.log('~-1 =', ~-1); // 0

// Formula: ~n = -(n + 1)
console.log('~5 = -(5+1) =', -(5 + 1)); // -6

// Double NOT for integer truncation
console.log('~~3.7 =', ~~3.7); // 3
console.log('~~-3.7 =', ~~-3.7); // -3 (note: different from Math.floor!)
console.log('Math.floor(-3.7) =', Math.floor(-3.7)); // -4

// IndexOf check trick
const arr = ['a', 'b', 'c'];
console.log("~arr.indexOf('b'):", ~arr.indexOf('b')); // -2 (truthy)
console.log("~arr.indexOf('z'):", ~arr.indexOf('z')); // 0 (falsy)

// ============================================
// EXAMPLE 6: Left Shift (<<)
// ============================================

console.log('\n--- Left Shift (<<) ---');

console.log('5 << 1 =', 5 << 1); // 10 (5 × 2)
console.log('5 << 2 =', 5 << 2); // 20 (5 × 4)
console.log('5 << 3 =', 5 << 3); // 40 (5 × 8)
console.log('1 << 10 =', 1 << 10); // 1024 (2^10)

// Creating bit masks
console.log('Bit mask at position 3:', (1 << 3).toString(2)); // 1000

// Fast multiplication by power of 2
const multiplyBy8 = (n) => n << 3;
console.log('7 × 8 =', multiplyBy8(7)); // 56

// ============================================
// EXAMPLE 7: Right Shift (>>)
// ============================================

console.log('\n--- Right Shift (>>) ---');

console.log('20 >> 1 =', 20 >> 1); // 10 (20 ÷ 2)
console.log('20 >> 2 =', 20 >> 2); // 5 (20 ÷ 4)

// Sign preserved for negative numbers
console.log('-20 >> 2 =', -20 >> 2); // -5

// Fast division by power of 2
const divideBy4 = (n) => n >> 2;
console.log('100 ÷ 4 =', divideBy4(100)); // 25

// ============================================
// EXAMPLE 8: Zero-fill Right Shift (>>>)
// ============================================

console.log('\n--- Zero-fill Right Shift (>>>) ---');

// Same for positive numbers
console.log('20 >> 2 =', 20 >> 2); // 5
console.log('20 >>> 2 =', 20 >>> 2); // 5

// Different for negative numbers!
console.log('-20 >> 2 =', -20 >> 2); // -5
console.log('-20 >>> 2 =', -20 >>> 2); // 1073741819

// Convert to unsigned 32-bit
console.log('-1 >>> 0 =', -1 >>> 0); // 4294967295 (max uint32)
console.log('-1 in binary (unsigned):', (-1 >>> 0).toString(2));

// ============================================
// EXAMPLE 9: Permission Flags System
// ============================================

console.log('\n--- Permission Flags System ---');

// Define permission flags
const NONE = 0b0000; // 0
const READ = 0b0001; // 1
const WRITE = 0b0010; // 2
const EXECUTE = 0b0100; // 4
const DELETE = 0b1000; // 8

// Create user permissions
let userPerms = READ | WRITE; // 3
console.log('User permissions (R+W):', userPerms.toString(2).padStart(4, '0'));

// Check permissions
const hasPermission = (perms, perm) => (perms & perm) !== 0;
console.log('Has READ?', hasPermission(userPerms, READ)); // true
console.log('Has EXECUTE?', hasPermission(userPerms, EXECUTE)); // false

// Add permission
userPerms = userPerms | EXECUTE;
console.log('After adding EXECUTE:', userPerms.toString(2).padStart(4, '0'));

// Remove permission
userPerms = userPerms & ~WRITE;
console.log('After removing WRITE:', userPerms.toString(2).padStart(4, '0'));

// Toggle permission
userPerms = userPerms ^ DELETE;
console.log('After toggling DELETE:', userPerms.toString(2).padStart(4, '0'));

// ============================================
// EXAMPLE 10: Color Manipulation
// ============================================

console.log('\n--- Color Manipulation ---');

// RGB to single number
const rgbToNumber = (r, g, b) => (r << 16) | (g << 8) | b;
const colorNum = rgbToNumber(255, 128, 64);
console.log('RGB(255, 128, 64) as number:', colorNum);
console.log('As hex:', colorNum.toString(16));

// Number to RGB
const numberToRgb = (n) => ({
  r: (n >> 16) & 0xff,
  g: (n >> 8) & 0xff,
  b: n & 0xff,
});
console.log('Back to RGB:', numberToRgb(colorNum));

// RGB to hex string
const rgbToHex = (r, g, b) => {
  return '#' + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
};
console.log('RGB(255, 128, 64) as hex:', rgbToHex(255, 128, 64));

// ============================================
// EXAMPLE 11: Bit Utilities
// ============================================

console.log('\n--- Bit Utilities ---');

// Check if power of 2
const isPowerOf2 = (n) => n > 0 && (n & (n - 1)) === 0;
console.log('isPowerOf2(16):', isPowerOf2(16)); // true
console.log('isPowerOf2(15):', isPowerOf2(15)); // false

// Count set bits
const countBits = (n) => {
  let count = 0;
  while (n) {
    count += n & 1;
    n >>>= 1;
  }
  return count;
};
console.log('Bits in 13 (1101):', countBits(13)); // 3
console.log('Bits in 255:', countBits(255)); // 8

// Get highest set bit position
const highestBit = (n) => Math.floor(Math.log2(n));
console.log('Highest bit position in 100:', highestBit(100)); // 6

// ============================================
// EXAMPLE 12: Simple XOR Encryption
// ============================================

console.log('\n--- XOR Encryption ---');

const encryptChar = (char, key) => char.charCodeAt(0) ^ key;
const decryptChar = (code, key) => String.fromCharCode(code ^ key);

const message = 'Hello';
const key = 42;

// Encrypt
const encrypted = [...message].map((c) => encryptChar(c, key));
console.log('Original:', message);
console.log('Encrypted codes:', encrypted);

// Decrypt
const decrypted = encrypted.map((code) => decryptChar(code, key)).join('');
console.log('Decrypted:', decrypted);

console.log('\n✅ All bitwise operator examples completed!');
Examples - JavaScript Tutorial | DeepML