{"id":353,"date":"2011-03-15T03:32:59","date_gmt":"2011-03-15T09:32:59","guid":{"rendered":"http:\/\/bateru.com\/news\/?p=353"},"modified":"2011-03-16T14:13:54","modified_gmt":"2011-03-16T20:13:54","slug":"javascript-binary-operations-the-easy-way","status":"publish","type":"post","link":"https:\/\/bateru.com\/news\/2011\/03\/javascript-binary-operations-the-easy-way\/","title":{"rendered":"JavaScript Binary Operations &#8211; the easy way"},"content":{"rendered":"<h2>Intro:<\/h2>\n<blockquote><p>\n\t&#8220;There are 10 types of people in this world. Those who understand binary and those who don&#8217;t&#8221; &#8211; Author Unknown\n\t<\/p><\/blockquote>\n<p>\tJavascript 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&#8217;m going to show you how to master them.<br \/>\n\tBy the end of this tutorial you will learn the following.<\/p>\n<ul>\n<li>Base Conversions<\/li>\n<li>Bitwise operations<\/li>\n<li>Logic Gates<\/li>\n<\/ul>\n<p>\tFor better comprehension, I recommend that you use a Javascript Console, which is available in <a href=\"http:\/\/getfirebug.com\/\">Firebug<\/a> ( a <a href=\"http:\/\/www.firefox.com\">Firefox<\/a> addon) or in <a href=\"http:\/\/code.google.com\/chrome\/devtools\/docs\/console.html\">Google Chrome Dev Tools<\/a>. If you wish, you can even use online editors, like <a href=\"http:\/\/www.jsbin.com\">jsbin.com<\/a> and <a href=\"http:\/\/jsfiddle.net\/\">jsfiddle.net<\/a>, to follow along.<br \/>\n<b>Note:<\/b> Negative numbers will not be dealt with in this tutorial, since Javascript doesn&#8217;t support signed bits.\n<\/p>\n<h2>Definitions:<\/h2>\n<p>\n\tFor those that are new to the binary concept, watch the following short videos to catch up then continue.<br \/>\t<br \/>\n\tDecimal, Binary, Octal, and Hexadecimal<br \/>\n\t<iframe loading=\"lazy\" title=\"YouTube video player\" width=\"480\" height=\"390\" src=\"http:\/\/www.youtube.com\/embed\/GRatBErTXg4\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<p>\tHexadecimal &#8211; learn it in less than a minute <br \/>\n\t<iframe loading=\"lazy\" title=\"YouTube video player\" width=\"640\" height=\"390\" src=\"http:\/\/www.youtube.com\/embed\/vkVklHXazZg\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<p>\tBoolean Algebra: AND\/OR\/NOT<br \/>\n\t<iframe loading=\"lazy\" title=\"YouTube video player\" width=\"480\" height=\"390\" src=\"http:\/\/www.youtube.com\/embed\/gnOP5uuXrrc\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<h2>Javascipt Code:<\/h2>\n<p>\n<b>Base Conversion: For positive numbers<\/b><br \/>\nThe toString() and parseInt() functions will be your friends in this section.<br \/>\n(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 &#8211; 36.<br \/>\n<b>Example:<\/b><\/p>\n<pre lang='javascript' line=\"1\">\r\n\/\/ number.toString( [ baseTo ] ); returns number in desired base.\r\n(3).toString( 2 ); \t\t\/\/ returns \"11\"\r\n(54).toString( 2 );\t\t\/\/ returns \"110110\"\r\n(120).toString( 16 );\t\t\/\/ returns \"78\"\r\n<\/pre>\n<p>Additionally, hexadecimal numbers( base 16) can be represented with a prefix of &#8220;0x&#8221;. <br \/>\nWhile a prefix of &#8220;0&#8221; denotes an Octal number( base 8).<br \/>\n<b>Example:<\/b><\/p>\n<pre lang='javascript' line=\"1\">\r\nvar hex = 0xFF\t\t\/\/ hex is 255 in decimal\r\nhex = 0x01 \t\t\/\/ now hex is 1 in decimal\r\nvar oct = 013\t\t\/\/ oct = 11\r\n<\/pre>\n<p>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 &#8211; 36.<br \/>\n<b>Example:<\/b><\/p>\n<pre lang='javascript' line=\"1\">\r\n\/\/ parseInt( { number | string }, [ baseFrom ] ); returns decimal number.\r\nnum = \"110110\";\r\nparseInt( num );\t\t\/\/ displays 110110 because default base 10.\r\nparseInt( num, 2 );\t\t\/\/ displays 54\r\nparseInt( \"dad\", 16 );\t\t\/\/ displays 3501, \"dad\" is valid hex;\r\n\r\nvar hex = \"badDad\";\t\r\nparseInt( hex, 16 );\t\t\/\/ returns 12246445\r\n+(\"0x\"+ hex );\t\t\t\/\/ returns 12246445 (Alternative way to parse hex.)\r\n<\/pre>\n<p>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.<br \/>\nFor those seeking a function to encode and decode bases higher than 36, check out this script at <a href=\"http:\/\/snipplr.com\/view\/139\/base-conversion\/\">Snipplr.com<\/a><\/p>\n<p><b>Example:<\/b><\/p>\n<pre lang='javascript' line=\"1\">\r\n\/\/ Convert from baseA( Binary ) to baseB( Hexadecimal). \r\n\/\/ Note: Both baseA and baseB must be between 2 and 36.\r\nvar baseA = 2, baseB = 16;\r\nvar binary = 1010111, hex, dec;\r\ndec = parseInt( binary, baseA );\t\t\/\/ dec = 87\r\nhex = dec.toString( baseB );\t\t\/\/ hex = 57\r\n<\/pre>\n<p>Thankfully, you can simplify all the base conversion to one simple function, which I call convertNumToBase.<\/p>\n<pre lang='javascript' line=\"1\">\r\n\/\/ Convert from baseA to baseB\r\n\/\/ Note: Both baseA and baseB must be between 2 and 36.\r\nvar convertNumToBase = function( num, baseA, baseB ){\r\n\tif( !( baseA < 2 || baseB < 2 || isNaN( baseA ) \r\n\t\t|| isNaN(baseB) || baseA > 36 || baseB > 36) ){\r\n        return parseInt( num, baseA ).toString( baseB );\r\n    }\r\n};\t\r\nconvertNumToBase( 1111, 2, 10 );\t\t\/\/ return \"15\"\r\nconvertNumToBase( 10101111, 2, 16 );\t\t\/\/ return \"af\"\r\nconvertNumToBase( \"FF\", 16, 2 ); \t\t\/\/ return \"11111111\"\r\n<\/pre>\n<p>\nSometimes, it might be useful to have a binary string with a fixed number of bits.<br \/>\nWe can implement this with an extension to the previous example.<\/p>\n<pre lang='javascript' line=\"1\">\r\nvar getStrCopy = function (str, copies) {\r\n\tvar newStr = str;\r\n\tcopies = (copies > 0) ? copies : 1;\r\n\twhile (--copies) {\r\n\t\tnewStr += str;\r\n\t}\r\n\treturn newStr;\r\n},\r\nconvertDecToBase = function ( dec, base, length, padding ) {\r\n\tpadding = padding || '0' ;\r\n\tvar num = dec.toString( base );\r\n\tlength = length || num.length;\r\n\tif (num.length !== length) {\r\n\t\tif (num.length < length) {\r\n\t\t\tnum = getStrCopy( padding, (length - num.length)) + num;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthrow new Error(\"convertDecToBase(): num(\" + num + \").length > length(\" + length + \") too long.\");\r\n\t\t}\r\n\t}\r\n\treturn num;\r\n};\r\n\r\n\/\/ Usage\r\nconvertDecToBase( 23, 2, 8 );            \/\/returns \"00010111\"\r\nconvertDecToBase( 23, 2, 8, 'x' );       \/\/returns \"xxx10111\"\r\n<\/pre>\n<p><b>Two&#8217;s Complement<\/b><br \/>\nJavascript designates the character tilde, ~, for the two&#8217;s complement, even though in most programming languages tilde represents a bit toggle for the one&#8217;s complement.<\/p>\n<pre lang=\"javascript\" line=\"1\">\r\nvar num = 70;\r\n~num;\t\t\t\/\/ returns -71\r\n~num.toString(2);\t\/\/ returns -1000111\r\n<\/pre>\n<p>I&#8217;ve already covered this feature in a previous article titled, &#8220;<a href=\"http:\/\/bateru.com\/news\/2011\/03\/javascript-not-is-not-what-you-expect\/\" alt=\"Javascript NOT is not what you expect\">Javascript NOT is not what you expect&#8221;<\/a>.<br \/>\n<br \/>\n<b>Proper Binary Format<\/b><br \/>\nTo make binary easier to read, modify the every four digits by either placing a space after them or converting them to hex.<\/p>\n<pre lang='javascript' line=\"1\">\r\nbinaryStr = \"1110001100110001\";\r\nbinaryStr.replace( \/\\d{4}\/g, '$& ' ).replace( \/\\s$\/,'') \/\/ return \"1110 0011 0011 0001\"\r\nparseInt( binaryStr, 2).toString( 16 );                   \/\/ returns \"e331\"\r\n<\/pre>\n<\/p>\n<p>\n<b>Bitwise operations<\/b><br \/>\nBitwise operations are covered in great details at <a href=\"http:\/\/en.wikipedia.org\/wiki\/Bitwise_operation\">Wikipedia: Bitwise Operations<\/a>.<br \/>\nBut if you don&#8217;t want to read that then watch this video.<br \/>\n<b>Note:<\/b> Remember Javascript&#8217;s tilde, ~, returns the two&#8217;s complement.<br \/>\n<iframe loading=\"lazy\" title=\"YouTube video player\" width=\"480\" height=\"390\" src=\"http:\/\/www.youtube.com\/embed\/d0AwjSpNXR0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n<p><b>Example:<\/b><\/p>\n<pre lang=\"javascript\" line=\"1\">\r\nclear();\r\nvar a = parseInt( \"1010\", 2 );\t\/\/ a = 10\r\nvar b = parseInt( \"1100\", 2 );\t\/\/ b = 12\r\n \r\n(a & b).toString(2);\t\t\/\/ a AND b returns dec = 8, binary = 1000\r\n(a | b).toString(2);\t        \/\/ a OR b returns dec = 14, binary = 1110\r\n(a ^ b);    \t\t        \/\/ a XOR b returns dec = 6, binary = 0110\r\n\r\n\/\/Invalid binary number because of the negative sign.\r\n~b.toString(2);     \t\t\/\/ a NOT returns dec = -13, binary = \"-1101\"\r\n(~( a & b )).toString(2); \t\/\/ a NAND b returns dec = -7, binary = \"-1001\"\r\n(~( a | b )).toString(2);\t\/\/ a NOR b returns dec = -15, binary = \"-1111\"\r\n~( a ^ b );                \t\/\/ a NXOR b returns dec = -7, binary = \"-1001\"\r\n \r\nvar num = 13; \t\t        \/\/ 13 is \"1101\" in binary;\r\nvar position = 3;\r\n \r\n\/\/ access bit position\r\n(num >> position).toString(2)\t\t\/\/ returns 1\r\n(num >> position) & 0x01;\t\t\/\/ returns 1\r\nnum.toString(2).charAt( position );\t\/\/ Alternative method, returns '1'\r\n \r\n\/\/ set a bit\r\n( 1 << position ).toString(2);\t\t\/\/ returns \"1000\"\r\nnum &#038;= ( 1 << position );\t\t\/\/ returns  8, binary \"1000\"\r\n \r\n\/\/ clear a bit\r\n( 0 << position ).toString(2);\t\t\/\/ returns \"1000\"\r\nnum &#038;= ( 0 << position );\t\t\/\/ returns 0\r\n \r\n\/\/ Toggle a bit\r\nnum ^= ( 1 << position );\t\t\/\/ returns 8, binary = \"1000\"\r\n \r\n\/\/ Test a bit\r\n(num >> position) & 1;\t\t\t\/\/returns 1\r\n \r\n\/\/ left shift with 0's\r\nnum >>> position;\t\t\t\/\/ returns 1\r\n \r\n\/\/ right shift with 0's\r\nnum << position;\t\t\t\/\/ returns 64, binary = \"1000000\"\r\n<\/pre>\n<\/p>\n<h2>Conclusion:<\/h2>\n<p>\nJavascript is a powerful language that many hidden features that waiting to be discovered.<br \/>\nEven though bitwise operations are rarely used in projects, it's still useful to know.<br \/>\nThis concludes the tutorial.<\/p>\n<p>Test your knowledge. <b>Take the quiz below!<\/b><br \/>\nBinary Quiz ( made with <a href=\"http:\/\/code.google.com\/p\/jquizme\/\">jQuizMe<\/a>)<\/p>\n<p><iframe src=\"http:\/\/bateru.com\/jquery\/jquizme_demo\/javascriptBitwiseQuiz.html\" frameborder=\"0\" style=\"width:30em;height:25em;\" alt=\"javascript bitwise quiz\"><br \/>\nVisit this link to take the <a href=\"http:\/\/bateru.com\/jquery\/jquizme_demo\/javascriptBitwiseQuiz.html\" alt=\"javascript bitwise quiz\"> Binary Quiz<\/a>.<br \/>\n<\/iframe><\/p>\n<h2>References:<\/h2>\n<p>\n\t<a href=\"https:\/\/developer.mozilla.org\/en\/JavaScript\/Reference\/Operators\/Bitwise_Operators\">Bitwise Operators<\/a><br \/>\n\t<a href=\"http:\/\/www.quotegarden.com\/computers.html\">More Geeky quotes<\/a><br \/>\n\t<a href=\"https:\/\/developer.mozilla.org\/en\/JavaScript\/Reference\/Global_Objects\/\">Javascript's Global Objects<\/a><br \/>\n\t<a href=\"http:\/\/en.wikipedia.org\/wiki\/Bitwise_operation\">Wikipedia Bitwise operations<\/a>\n<\/p>\n<p>\n<iframe src=\"http:\/\/rcm.amazon.com\/e\/cm?lt1=_blank&#038;bc1=FFFFFF&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=baterucom-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;ref=tf_til&#038;asins=B001D8NN1Q\" style=\"width:120px;height:240px;\" scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\"><\/iframe><br \/>\n<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Intro: &#8220;There are 10 types of people in this world. Those who understand binary and those who don&#8217;t&#8221; &#8211; 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&#8217;m going to show you how to &hellip; <a href=\"https:\/\/bateru.com\/news\/2011\/03\/javascript-binary-operations-the-easy-way\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">JavaScript Binary Operations &#8211; the easy way<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,12,10],"tags":[55,56,164,16],"class_list":["post-353","post","type-post","status-publish","format-standard","hentry","category-frontend-tech","category-science","category-tutorials","tag-bitwise-operations","tag-howto","tag-javascript","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/353","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/comments?post=353"}],"version-history":[{"count":24,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/353\/revisions"}],"predecessor-version":[{"id":429,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/353\/revisions\/429"}],"wp:attachment":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/media?parent=353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/categories?post=353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/tags?post=353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}