How to usebitwise operations in Javascript
- We are using bitwise operations to mark multiples of 2 or 5 in an array efficiently.
- It checks bits for divisibility, sets appropriate bits, and prints multiples from 2 to 10 using bitwise manipulation.
Example: In the example we see Space optimization using bit manipulations in JavaScript array using bitwise operations
Javascript
function checkbit(array, index) { return array[index >> 5] & (1 << (index & 31)); } // Sets value of bit for corresponding index function setbit(array, index) { array[index >> 5] |= (1 << (index & 31)); } // Driver code let a = 2, b = 10; let size = Math.abs(b - a); size = Math.ceil(size / 32); let array = new Array(size); for (let i = a; i <= b; i++) if (i % 2 == 0 || i % 5 == 0) setbit(array, i - a); console.log( "MULTIPLES of 2 and 5:" ); for (let i = a; i <= b; i++) if (checkbit(array, i - a)) console.log(i); |
MULTIPLES of 2 and 5: 2 4 5 6 8 10
JavaScript Program for Space Optimization Using bit Manipulations
Space optimization using bit manipulations refers to a technique where data is stored in a compact form using individual bits to represent values, reducing memory usage compared to traditional data structures. This method is efficient for managing and storing binary or boolean information, saving space in memory.
Examples:
Input : 2 10
Output : 2 4 5 6 8 10
Input: 60 95
Output: 60 62 64 65 66 68 70 72 74 75 76 78
80 82 84 85 86 88 90 92 94 95
Table of Content
- Using a bitmask
- Using bitwise operations