JavaScript decbin
Returns a string containing a binary representation of the number
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 | function decbin (number) { // Returns a string containing a binary representation of the number // // version: 909.322 // discuss at: http://phpjs.org/functions/decbin // + original by: Enrique Gonzalez // + bugfixed by: Onno Marsman // + improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript // + input by: pilus // + input by: nord_ua // * example 1: decbin(12); // * returns 1: '1100' // * example 2: decbin(26); // * returns 2: '11010' // * example 3: decbin('26'); // * returns 3: '11010' if (number < 0) { number = 0xFFFFFFFF + number + 1; } return parseInt(number, 10).toString(2);} |
Examples
» Example 1
Running
1 | decbin(12); |
Should return
1 | '1100' |
» Example 2
Running
1 | decbin(26); |
Should return
1 | '11010' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have decbin goodness in JavaScript.
Please note that there is a difference between the handling of large numbers in different browsers. e.g.
IE8
1 2 | >>decbin(3747030078639374300) "1.101000000000000100000000000010000000000000001(e+61)" |
Firefox 3.5
1 2 | >>> decbin(3747030078639374300) "11010000000000001000000000000100000000000000010000000000000000" |
This is caused by the fact that Number.toString(2) doesn't work in IE for numbers written in scientific notation internally.



Kevin van Zonneveld
16 Aug '09