Convert int to binary 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] 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

Chủ Đề