Last active
March 3, 2017 14:39
-
-
Save iSkore/0279066373d48de2ad1c15f78c361a06 to your computer and use it in GitHub Desktop.
Binary fun. Learn you some binary.
This file contains 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 strict'; | |
// only works for binary numbers 0-15 to help with understanding binary | |
function coerceToBinary( n ) { | |
n = n === +n ? ( n >>> 0 ).toString( 2 ) : n; | |
if( n < 0 ) | |
return coerceToBinary( n ); | |
if( n.length === 6 && n.startsWith( '0b' ) ) | |
return n; | |
else if( n.length > 6 ) | |
return coerceToBinary( ( ''+n ).substr( n.length - 4, n.length ) ); | |
else if( n.length === 4 ) | |
return '0b' + n; | |
else if( n.length === 3 ) | |
return '0b0' + n; | |
else if( n.length === 2 ) | |
return '0b00' + n; | |
else if( n.length === 1 ) | |
return '0b000' + n; | |
return n; | |
} | |
const ctb = n => console.log( coerceToBinary( n ) ); | |
// Logical operators | |
// Logical AND | |
ctb( 0b1100 & 0b1010 ); // 0b1000 or 8 | |
// Logical OR | |
ctb( 0b0100 | 0b0010 ); // 0b0110 or 6 | |
// Logical NOT | |
ctb( ~0b0101 ); // 0b1010 or 10 | |
// Logical XOR | |
ctb( 0b0101 ^ 0b0001 ); // 0b0100 or 4 | |
// Logical Left Shift | |
ctb( 0b0101 << 1 ); // 0b1010 or 10 | |
// Logical Right Shift | |
ctb( 0b0101 >> 1 ); // 0b0010 or 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment