Created
June 3, 2020 15:07
-
-
Save AlexanderHentzsch/a3490584d408ca0bfd71965030cb0d92 to your computer and use it in GitHub Desktop.
Usage of bit operators for function selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>JS Bitwise Operators</title> | |
| <meta charset="UTF-8" /> | |
| </head> | |
| <body> | |
| <div id="app"></div> | |
| <script src="src/index.js"></script> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Use only Bitnumbers for identification | |
| const func1 = 1; // 0001 | |
| const func2 = 2; // 0010 | |
| const func3 = 4; // 0100 | |
| const func4 = 8; // 1000 | |
| // Use pipes to select multiple functions | |
| const user = func1 | func2 | func4; | |
| let useFunc1 = (user & func1) !== 0; | |
| let useFunc2 = (user & func2) !== 0; | |
| let useFunc3 = (user & func3) !== 0; | |
| let useFunc4 = (user & func4) !== 0; | |
| // *.toString() convert boolean to string for output | |
| document.getElementById("app").innerHTML = ` | |
| <h1>JS Simple Bitwise Operators</h1> | |
| <div> | |
| User: ${dec2bin(user)}<br/> | |
| Use Function 1 : ${useFunc1.toString()}<br/> | |
| Use Function 2 : ${useFunc2.toString()}<br/> | |
| Use Function 3 : ${useFunc3.toString()}<br/> | |
| Use Function 4 : ${useFunc4.toString()}<br/> | |
| </div> | |
| `; | |
| function dec2bin(dec) { | |
| return (dec >>> 0).toString(2).padStart(8, "0"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment