JavaScript Binary Operations – the easy way


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Intro:

“There are 10 types of people in this world. Those who understand binary and those who don’t” – Author Unknown

Javascript is loaded with hidden features that can that be used for more than DOM manipulation and event handling. Javascript supports binary operations pretty well, and now I’m going to show you how to master them.
By the end of this tutorial you will learn the following.

  • Base Conversions
  • Bitwise operations
  • Logic Gates

For better comprehension, I recommend that you use a Javascript Console, which is available in Firebug ( a Firefox addon) or in Google Chrome Dev Tools. If you wish, you can even use online editors, like jsbin.com and jsfiddle.net, to follow along.
Note: Negative numbers will not be dealt with in this tutorial, since Javascript doesn’t support signed bits.

Definitions:

For those that are new to the binary concept, watch the following short videos to catch up then continue.

Decimal, Binary, Octal, and Hexadecimal

Hexadecimal – learn it in less than a minute

Boolean Algebra: AND/OR/NOT

Javascipt Code:

Base Conversion: For positive numbers
The toString() and parseInt() functions will be your friends in this section.
(number).toString( [baseTo] ) will change a number to a string type. If a base is provided in the toString argument, then the number gets converted to a new base from 2 – 36.
Example:

1
2
3
4
// number.toString( [ baseTo ] ); returns number in desired base.
(3).toString( 2 ); 		// returns "11"
(54).toString( 2 );		// returns "110110"
(120).toString( 16 );		// returns "78"

Additionally, hexadecimal numbers( base 16) can be represented with a prefix of “0x”.
While a prefix of “0” denotes an Octal number( base 8).
Example:

1
2
3
var hex = 0xFF		// hex is 255 in decimal
hex = 0x01 		// now hex is 1 in decimal
var oct = 013		// oct = 11

Alternatively, parseInt( { number | string }, [baseFrom] ) will parse a number or a string that contains a number, and convert the bases, with the default base set to 10. Please be aware that you the base must be between 2 – 36.
Example:

1
2
3
4
5
6
7
8
9
// parseInt( { number | string }, [ baseFrom ] ); returns decimal number.
num = "110110";
parseInt( num );		// displays 110110 because default base 10.
parseInt( num, 2 );		// displays 54
parseInt( "dad", 16 );		// displays 3501, "dad" is valid hex;
 
var hex = "badDad";	
parseInt( hex, 16 );		// returns 12246445
+("0x"+ hex );			// returns 12246445 (Alternative way to parse hex.)

Ok, so your next question might be how to convert from one base to another, like from Binary to Hexadecimal. To achieve your goal, convert base A to decimal then to base B.
For those seeking a function to encode and decode bases higher than 36, check out this script at Snipplr.com

Example:

1
2
3
4
5
6
// Convert from baseA( Binary ) to baseB( Hexadecimal). 
// Note: Both baseA and baseB must be between 2 and 36.
var baseA = 2, baseB = 16;
var binary = 1010111, hex, dec;
dec = parseInt( binary, baseA );		// dec = 87
hex = dec.toString( baseB );		// hex = 57

Thankfully, you can simplify all the base conversion to one simple function, which I call convertNumToBase.

1
2
3
4
5
6
7
8
9
10
11
// Convert from baseA to baseB
// Note: Both baseA and baseB must be between 2 and 36.
var convertNumToBase = function( num, baseA, baseB ){
	if( !( baseA < 2 || baseB < 2 || isNaN( baseA ) 
		|| isNaN(baseB) || baseA > 36 || baseB > 36) ){
        return parseInt( num, baseA ).toString( baseB );
    }
};	
convertNumToBase( 1111, 2, 10 );		// return "15"
convertNumToBase( 10101111, 2, 16 );		// return "af"
convertNumToBase( "FF", 16, 2 ); 		// return "11111111"

Sometimes, it might be useful to have a binary string with a fixed number of bits.
We can implement this with an extension to the previous example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var getStrCopy = function (str, copies) {
	var newStr = str;
	copies = (copies > 0) ? copies : 1;
	while (--copies) {
		newStr += str;
	}
	return newStr;
},
convertDecToBase = function ( dec, base, length, padding ) {
	padding = padding || '0' ;
	var num = dec.toString( base );
	length = length || num.length;
	if (num.length !== length) {
		if (num.length < length) {
			num = getStrCopy( padding, (length - num.length)) + num;
		}
		else {
			throw new Error("convertDecToBase(): num(" + num + ").length > length(" + length + ") too long.");
		}
	}
	return num;
};
 
// Usage
convertDecToBase( 23, 2, 8 );            //returns "00010111"
convertDecToBase( 23, 2, 8, 'x' );       //returns "xxx10111"

Two’s Complement
Javascript designates the character tilde, ~, for the two’s complement, even though in most programming languages tilde represents a bit toggle for the one’s complement.

1
2
3
var num = 70;
~num;			// returns -71
~num.toString(2);	// returns -1000111

I’ve already covered this feature in a previous article titled, “Javascript NOT is not what you expect”.

Proper Binary Format
To make binary easier to read, modify the every four digits by either placing a space after them or converting them to hex.

1
2
3
binaryStr = "1110001100110001";
binaryStr.replace( /\d{4}/g, '$& ' ).replace( /\s$/,'') // return "1110 0011 0011 0001"
parseInt( binaryStr, 2).toString( 16 );                   // returns "e331"

Bitwise operations
Bitwise operations are covered in great details at Wikipedia: Bitwise Operations.
But if you don’t want to read that then watch this video.
Note: Remember Javascript’s tilde, ~, returns the two’s complement.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
clear();
var a = parseInt( "1010", 2 );	// a = 10
var b = parseInt( "1100", 2 );	// b = 12
 
(a & b).toString(2);		// a AND b returns dec = 8, binary = 1000
(a | b).toString(2);	        // a OR b returns dec = 14, binary = 1110
(a ^ b);    		        // a XOR b returns dec = 6, binary = 0110
 
//Invalid binary number because of the negative sign.
~b.toString(2);     		// a NOT returns dec = -13, binary = "-1101"
(~( a & b )).toString(2); 	// a NAND b returns dec = -7, binary = "-1001"
(~( a | b )).toString(2);	// a NOR b returns dec = -15, binary = "-1111"
~( a ^ b );                	// a NXOR b returns dec = -7, binary = "-1001"
 
var num = 13; 		        // 13 is "1101" in binary;
var position = 3;
 
// access bit position
(num >> position).toString(2)		// returns 1
(num >> position) & 0x01;		// returns 1
num.toString(2).charAt( position );	// Alternative method, returns '1'
 
// set a bit
( 1 << position ).toString(2);		// returns "1000"
num &= ( 1 << position );		// returns  8, binary "1000"
 
// clear a bit
( 0 << position ).toString(2);		// returns "1000"
num &= ( 0 << position );		// returns 0
 
// Toggle a bit
num ^= ( 1 << position );		// returns 8, binary = "1000"
 
// Test a bit
(num >> position) & 1;			//returns 1
 
// left shift with 0's
num >>> position;			// returns 1
 
// right shift with 0's
num << position;			// returns 64, binary = "1000000"

Conclusion:

Javascript is a powerful language that many hidden features that waiting to be discovered.
Even though bitwise operations are rarely used in projects, it’s still useful to know.
This concludes the tutorial.

Test your knowledge. Take the quiz below!
Binary Quiz ( made with jQuizMe)

References:

Bitwise Operators
More Geeky quotes
Javascript’s Global Objects
Wikipedia Bitwise operations


Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Javascript NOT is not what you expect


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Not gate
Not gate

A weird part of javascript is trying to toggle the bits in a number. For most programming languages, like C and Java, ~ represents a bitwise NOT operation, aka one’s complement. But in javascript, ~ produces the two’s complement. Since ~num gives the two’s complement, equivalent to -(num + 1), then one would suspect that ~(num -1) should give back the one’s complement.
However that’s not the case, as the next example demonstrates.

1
2
3
4
var num = 9;
num.toString(2);            //returns 1001
(~num).toString(2);	// returns "-1010"
~(num - 1).toString(2);    //returns "-1001"

As you can see from the example, there are two main problems. The first is that the sign bit is replaced with a negative sign. And second, the bits don’t get toggled.
To fix this problem most programmers would just XOR the number with a mask to toggle the bits. Although this works, it quickly produces the unintended result once you XOR a number larger than the mask.
Example:

1
2
3
4
5
var BIT_MASK = 0xF;
(9).toString(2);			//returns "1001"
(9 ^ BIT_MASK).toString(2);		//returns "110"
(30).toString(2);			//returns "11110"
(30 ^ BIT_MASK).toString(2);		//returns "10001"

A simple solution to this problem is to not to use javascript for bitwise operations.
However, if javascript is required then use the following code to implement bitwise NOT operation.
Method 1: Simple approach.

1
2
3
4
5
6
7
8
9
var toggleBits = function( dec ){
    var mask = 0xFFFFFFF;
    return ( dec ^ mask ).toString(2).match( RegExp( "[01]{"+(dec.toString(2).length)+"}$" ) )[0];
};
 
var num = 23;
num.toString(2);		// returns 10111
num = toggleBits(num);	        // num = 01000;
num = parseInt( num, 2);	// num = 8, binary = 1000

Method 2: More advance features.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Programer: Larry Battle
// Purpose: Provide a bit toggle function for javascript.
var getStrCopy = function (str, copies) {
	var newStr = str;
	copies = (copies > 0) ? copies : 1;
	while (--copies) {
		newStr += str;
	}
	return newStr;
};
var convertDecToBase = function ( dec, base, length, padding ) {
	padding = padding || '0' ;
	var num = dec.toString( base );
	length = length || num.length;
	if (num.length !== length) {
		if (num.length > length) {
			throw new Error("convertDecToBase(): num(" + num + ") > length(" + length + ") too long.");
		}
		num = getStrCopy( padding, (length - num.length)) + num;
	}
	return num;
};
var formatBinaryStr = function( str ){
    return str.replace( /\d{4}/g, '$& ' ).replace( /\s$/,'');
};
var toggleBits = function( dec, length, doFormat ){
    var str = convertDecToBase( dec, 2, length || 8 );
    var binaryStr = str.replace( /0/g, 'o' ).replace( /1/g, '0').replace( /o/g, '1' );
    return ( doFormat ) ? formatBinaryStr( binaryStr ) : binaryStr ;
};
 
// The following requires Firebug or Google Chrome Dev Tools
clear();
 
// Test case
var num = 230;
var testNum = parseInt( toggleBits(num), 2 );
testNum = parseInt( toggleBits( testNum ), 2 );
console.log( "(Test Case) 2 Bit Toggles will give the original number: " +  (testNum == num) );
 
// Examples: 
console.log( toggleBits( 1 ) );    // displays "11111110"
console.log( toggleBits( 2 ) );    // displays "11111101"
console.log( toggleBits( 50, 16 ) );// displays "1111111111001101"
console.log( toggleBits( 15, 8, true ) );    // displays "1111 0000"
console.log( toggleBits( 520, 16, true ) ); // displays "1111 1101 1111 0111"

For more information check out Mozilla’s Bitwise Operators Reference

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Best way to prevent Javascript from failing.

Javascript is a great flexible language but has a major flaw with portability. I call it the “1 Hit Combo super punchy epic fail” error, aka Error Object. The Error object has 6 beautiful children that everyone hates to see. Their names are EvalError, RangeError, ReferenceError, SyntaxError, TypeError and URIError, and your task a good professional Frontend programmer is to prevent those 7 object from never stepping foot onto your website. So here are some simple tips to assist you in your struggle.


Solution 1:
First off, you should check your code to make sure that you’re not the one causing the errors message.
So check your code with code analysis tools like JSlint, console2 (a firefox addon ) or Google’s Closure inspector.

Solution 2:
If possible you could also wrap your error prone code in try or catch blocks.
Try and Catch works as follow.

Sends an error message to the browser and further Javascript from executing.

1
2
var obj = [];
obj[0] = globalVar;    //ERROR!

Send the error message to the catch block and let’s the developer decide what to do.

1
2
3
4
5
6
7
try{
    var obj = [];
    obj[0] = globalVar;
}
catch( err ){
    alert( "Error Message: " + err.message ); //You should log the error instead of alert it.
}

Solution 3:
For a page that requires javascript, you can load that page with a iframe. With a iframe or frame, even if your main page halts due to an error, your javascript in your iframe will continue to run.

1
2
3
<iframe src="javascript_page.html" width="100%" height="30">
  <p>Your browser does not support iframes.</p>
</iframe>

For something else that might help, check out ADSAFE (protection against 3rd party scripts).

References:
MDN Doc Center: Error
Stackoverflow : Is it possible to “sandbox” arbitrary JavaScript to only operate on one div and not the whole document?

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the day – Javascript Insertion Sort

Insertion Sort.
Best: O(n), Average: O(n2), Worst: O(n2)
Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time.
Visit Wikipedia for more information.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Programmer: Larry Battle Mar 9, 2011
//Purpose: Insertion sort implemented in Javascript.
var insertionSort = function (arr) {
    var len = arr.length, i = -1, j, tmp;
 
    while (len--) {
        tmp = arr[++i];
        j = i;
        while (j-- && arr[j] > tmp) {
            arr[j + 1] = arr[j];
        }
        arr[j + 1] = tmp;
    }
};

Usage

1
2
insertionSort( [5,4,3,2,1] ); //returns [1,2,3,4,5];
insertionSort( [ "bear", "dog", "cat" ] ) // returns ["bear", "cat", "dog"];

Demo

Jsbin.com
bateru.com/uploads

Here’s a great short video tutorial to help those clueless about insertion sort.


Update:

/**
* Sorts an array using insertion sort.
* 
* @param {Array} - arr
* @param {Boolean} areNumbers indicates whether the array elements should be cast as numbers.
* @return {Array} the sorted array.
*/
var insertionSort = function (arr, areNumbers) {
	arr = arr.concat();
	var len = arr.length,
	i = -1,
	j,
	tmp;
	while (len--) {
		tmp = arr[++i];
		j = i;
		while (j-- && areNumbers ? (+arr[j] > +tmp) : (arr[j] > tmp) ) {
			arr[j + 1] = arr[j];
		}
		arr[j + 1] = tmp;
	}
	return arr;
};
// Treat input as array of numbers
Input: insertionSort(["1","2","3","4","4","40","20","21"], true);
Output: ["1", "2", "3", "4", "4", "20", "21", "40"]
 
// Treat input as array of strings
Input: insertionSort(["1","2","3","4","4","40","20","21"]);
Output: ["1", "2", "20", "21", "3", "4", "4", "40"]

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube