How do I convert an integer to binary in JavaScript?
A solution i'd go with that's fine for 32-bits, is the code the end of this answer, which is from developer.mozilla.org(MDN), but with some lines added for A)formatting and B)checking that the number is in range.
Some suggested x.toString(2)
which doesn't work for negatives, it just sticks a minus sign in there for them, which is no good.
Fernando mentioned a simple solution of (x>>>0).toString(2);
which is fine for negatives, but has a slight issue when x is positive. It has the output starting with 1, which for positive numbers isn't proper 2s complement.
Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?
A solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. And one could accept sometimes having a 33bit number, or one could make sure that the number to convert is within range -(2^31)<=x<2^31-1. So the number is always 32bits. But rather than do that, you can go with this solution on mozilla.org
Patrick's answer and code is long and apparently works for 64-bit, but had a bug that a commenter found, and the commenter fixed patrick's bug, but patrick has some "magic number" in his code that he didn't comment about and has forgotten about and patrick no longer fully understands his own code / why it works.
Annan had some incorrect and unclear terminology but mentioned a solution by developer.mozilla.org
Note- the old link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators now redirects elsewhere and doesn't have that content but the proper old link , which comes up when archive.org retrieves pages!, is available here https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
The solution there works for 32-bit numbers.
The code is pretty compact, a function of three lines.
But I have added a regex to format the output in groups of 8 bits. Based on How to print a number with commas as thousands separators in JavaScript (I just amended it from grouping it in 3s right to left and adding commas, to grouping in 8s right to left, and adding spaces)
And, while mozilla made a comment about the size of nMask(the number fed in)..that it has to be in range, they didn't test for or throw an error when the number is out of range, so i've added that.
I'm not sure why they named their parameter 'nMask' but i'll leave that as is.
https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
function createBinaryString(nMask) {
// nMask must be between -2147483648 and 2147483647
if (nMask > 2**31-1)
throw "number too large. number shouldn't be > 2**31-1"; //added
if (nMask < -1*(2**31))
throw "number too far negative, number shouldn't be < 2**31" //added
for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
sMask=sMask.replace(/\B(?=(.{8})+(?!.))/g, " ") // added
return sMask;
}
console.log(createBinaryString(-1)) // "11111111 11111111 11111111 11111111"
console.log(createBinaryString(1024)) // "00000000 00000000 00000100 00000000"
console.log(createBinaryString(-2)) // "11111111 11111111 11111111 11111110"
console.log(createBinaryString(-1024)) // "11111111 11111111 11111100 00000000"
//added further console.log example
console.log(createBinaryString(2**31 -1)) //"01111111 11111111 11111111 11111111"
String Conversion in Javascript (Decimal to Binary)
try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString
method of javascript Number
objects overrides the toString
method of Object
objects to accept an optional radix as an argument to provide the functionality you are looking for. The String
object does not override Object
's toString
method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp
parseInt not converting decimal to binary?
parseInt(number, base)
returns decimal value of a number presented by number
parameter in base
base.
And 11 is binary equivalent of 3 in decimal number system.
var a = {};
window.addEventListener('input', function(e){ a[e.target.name] = e.target.value; console.clear(); console.log( parseInt(a.number, a.base) );}, false);
<input name='number' placeholder='number' value='1010'><input name='base' placeholder='base' size=3 value='2'>
JavaScript - Convert decimal number to 4-bit binary number in the form of String
Use padStart
The
padStart()
method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
var t1 = parseInt(4, 10).toString(2).padStart(4, "0")
var t2 = parseInt(15, 10).toString(2).padStart(4, "0")
console.log(t1)
console.log(t2)
Javascript - convert integer to array of bits
convert to base 2:
var base2 = (yourNumber).toString(2);
access the characters (bits):
base2[0], base2[1], base2[3], etc...
Related Topics
JavaScript Math, Round to Two Decimal Places
Angularjs - Any Way for $Http.Post to Send Request Parameters Instead of JSON
Communication Between Sibling Components in Vue.Js 2.0
Get the Value of Checked Checkbox
How to Create Multidimensional Array
When and Why to 'Return False' in JavaScript
Get Time Difference Between Two Dates in Seconds
Using JavaScript to Display a Blob
Does Never Resolved Promise Cause Memory Leak
How to Get the Fragment Identifier (Value After Hash #) from a Url
Removing an Anonymous Event Listener
How Does Asynchronous JavaScript Execution Happen? and When Not to Use Return Statement
Merge Multiple Objects Inside the Same Array into One Object
Get First and Last Date of Current Month with JavaScript or Jquery
Convert a Binary Nodejs Buffer to JavaScript Arraybuffer
How to Get Notified About Changes of the History via History.Pushstate