简体   繁体   中英

How do I convert an integer to binary in JavaScript?

I'd like to see integers, positive or negative, in binary.

Rather like this question , but for JavaScript.

 function dec2bin(dec) { return (dec >>> 0).toString(2); } console.log(dec2bin(1)); // 1 console.log(dec2bin(-1)); // 11111111111111111111111111111111 console.log(dec2bin(256)); // 100000000 console.log(dec2bin(-256)); // 11111111111111111111111100000000

You can use Number.toString(2) function, but it has some problems when representing negative numbers. For example, (-1).toString(2) output is "-1" .

To fix this issue, you can use the unsigned right shift bitwise operator ( >>> ) to coerce your number to an unsigned integer.

If you run (-1 >>> 0).toString(2) you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111" correctly.

This question has further explanation.

-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.

Try

num.toString(2);

The 2 is the radix and can be any base between 2 and 36

source here

UPDATE:

This will only work for positive numbers, Javascript represents negative binary integers in two's-complement notation. I made this little function which should do the trick, I haven't tested it out properly:

function dec2Bin(dec)
{
    if(dec >= 0) {
        return dec.toString(2);
    }
    else {
        /* Here you could represent the number in 2s compliment but this is not what 
           JS uses as its not sure how many bits are in your number range. There are 
           some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit 
        */
        return (~dec).toString(2);
    }
}

I had some help from here

A simple way is just...

Number(42).toString(2);

// "101010"

The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer )

1. Number System

(123456).toString(2) will convert numbers to the base 2 positional numeral system . In this system negative numbers are written with minus signs just like in decimal.

2. Internal Representation

The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer . There is no easy way to create a bit-string representation of this in javascript nor access specific bits.

3. Masks & Bitwise Operators

MDN has a good overview of how bitwise operators work. Importantly:

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)

Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.

Here is the MDN example code for converting numbers into 32-bit strings.

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

This answer attempts to address inputs with an absolute value in the range of 2147483648 10 (2 31 ) – 9007199254740991 10 (2 53 -1).


In JavaScript, numbers are stored in 64-bit floating point representation , but bitwise operations coerce them to 32-bit integers in two's complement format , so any approach which uses bitwise operations restricts the range of output to -2147483648 10 (-2 31 ) – 2147483647 10 (2 31 -1).

However, if bitwise operations are avoided and the 64-bit floating point representation is preserved by using only mathematical operations, we can reliably convert any safe integer to 64-bit two's complement binary notation by sign-extending the 53-bit twosComplement :

 function toBinary (value) { if (!Number.isSafeInteger(value)) { throw new TypeError('value must be a safe integer'); } const negative = value < 0; const twosComplement = negative ? Number.MAX_SAFE_INTEGER + value + 1 : value; const signExtend = negative ? '1' : '0'; return twosComplement.toString(2).padStart(53, '0').padStart(64, signExtend); } function format (value) { console.log(value.toString().padStart(64)); console.log(value.toString(2).padStart(64)); console.log(toBinary(value)); } format(8); format(-8); format(2**33-1); format(-(2**33-1)); format(2**53-1); format(-(2**53-1)); format(2**52); format(-(2**52)); format(2**52+1); format(-(2**52+1));
 .as-console-wrapper{max-height:100%!important}

For older browsers, polyfills exist for the following functions and values:

As an added bonus, you can support any radix (2–36) if you perform the two's complement conversion for negative numbers in ⌈64 / log 2 (radix)⌉ digits by using BigInt :

 function toRadix (value, radix) { if (!Number.isSafeInteger(value)) { throw new TypeError('value must be a safe integer'); } const digits = Math.ceil(64 / Math.log2(radix)); const twosComplement = value < 0 ? BigInt(radix) ** BigInt(digits) + BigInt(value) : value; return twosComplement.toString(radix).padStart(digits, '0'); } console.log(toRadix(0xcba9876543210, 2)); console.log(toRadix(-0xcba9876543210, 2)); console.log(toRadix(0xcba9876543210, 16)); console.log(toRadix(-0xcba9876543210, 16)); console.log(toRadix(0x1032547698bac, 2)); console.log(toRadix(-0x1032547698bac, 2)); console.log(toRadix(0x1032547698bac, 16)); console.log(toRadix(-0x1032547698bac, 16));
 .as-console-wrapper{max-height:100%!important}

If you are interested in my old answer that used an ArrayBuffer to create a union between a Float64Array and a Uint16Array , please refer to this answer's revision history .

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"

You can write your own function that returns an array of bits. Example how to convert number to bits

Divisor| Dividend| bits/remainder

2 | 9 | 1

2 | 4 | 0

2 | 2 | 0

~ | 1 |~

example of above line: 2 * 4 = 8 and remainder is 1 so 9 = 1 0 0 1

function numToBit(num){
    var number = num
    var result = []
    while(number >= 1 ){
        result.unshift(Math.floor(number%2))
        number = number/2
    }
    return result
}

Read remainders from bottom to top. Digit 1 in the middle to top.

This is how I manage to handle it:

const decbin = nbr => {
  if(nbr < 0){
     nbr = 0xFFFFFFFF + nbr + 1
  }
  return parseInt(nbr, 10).toString(2)
};

got it from this link: https://locutus.io/php/math/decbin/

we can also calculate the binary for positive or negative numbers as below:

 function toBinary(n){ let binary = ""; if (n < 0) { n = n >>> 0; } while(Math.ceil(n/2) > 0){ binary = n%2 + binary; n = Math.floor(n/2); } return binary; } console.log(toBinary(7)); console.log(toBinary(-7));

You could use a recursive solution:

 function intToBinary(number, res = "") { if (number < 1) if (res === "") return "0" else return res else return intToBinary(Math.floor(number / 2), number % 2 + res) } console.log(intToBinary(12)) console.log(intToBinary(546)) console.log(intToBinary(0)) console.log(intToBinary(125))
Works only with positive numbers.

I'd like to see integers, positive or negative, in binary.

This is an old question and I think there are very nice solutions here but there is no explanation about the use of these clever solutions.

First, we need to understand that a number can be positive or negative. Also, JavaScript provides a MAX_SAFE_INTEGER constant that has a value of 9007199254740991 . The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 - 1) and 2^53 - 1 .

So, now we know the range where numbers are "safe". Also, JavaScript ES6 has the built-in method Number.isSafeInteger() to check if a number is a safe integer.

Logically, if we want to represent a number n as binary, this number needs a length of 53 bits, but for better presentation lets use 7 groups of 8 bits = 56 bits and fill the left side with 0 or 1 based on its sign using the padStart function.

Next, we need to handle positive and negative numbers: positive numbers will add 0 s to the left while negative numbers will add 1 s. Also, negative numbers will need a two's-complement representation. We can easily fix this by adding Number.MAX_SAFE_INTEGER + 1 to the number.

For example, we want to represent -3 as binary, lets assume that Number.MAX_SAFE_INTEGER is 00000000 11111111 (255) then Number.MAX_SAFE_INTEGER + 1 will be 00000001 00000000 (256) . Now lets add the number Number.MAX_SAFE_INTEGER + 1 - 3 this will be 00000000 11111101 (253) but as we said we will fill with the left side with 1 like this 11111111 11111101 (-3) , this represent -3 in binary.

Another algorithm will be we add 1 to the number and invert the sign like this -(-3 + 1) = 2 this will be 00000000 00000010 (2) . Now we invert every bit like this 11111111 11111101 (-3) again we have a binary representation of -3 .

Here we have a working snippet of these algos:

 function dec2binA(n) { if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer') if (n > 2**31) throw 'number too large. number should not be greater than 2**31' if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31' const bin = n < 0 ? Number.MAX_SAFE_INTEGER + 1 + n : n const signBit = n < 0 ? '1' : '0' return parseInt(bin, 10).toString(2) .padStart(56, signBit) .replace(/\B(?=(.{8})+(?!.))/g, ' ') } function dec2binB(n) { if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer') if (n > 2**31) throw 'number too large. number should not be greater than 2**31' if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31' const bin = n < 0 ? -(1 + n) : n const signBit = n < 0 ? '1' : '0' return parseInt(bin, 10).toString(2) .replace(/[01]/g, d => +!+d) .padStart(56, signBit) .replace(/\B(?=(.{8})+(?!.))/g, ' ') } const a = -805306368 console.log(a) console.log('dec2binA:', dec2binA(a)) console.log('dec2binB:', dec2binB(a)) const b = -3 console.log(b) console.log('dec2binA:', dec2binA(b)) console.log('dec2binB:', dec2binB(b))

One more alternative

const decToBin = dec => {
  let bin = '';
  let f = false;

  while (!f) {
    bin = bin + (dec % 2);    
    dec = Math.trunc(dec / 2);  

    if (dec === 0 ) f = true;
  }

  return bin.split("").reverse().join("");
}

console.log(decToBin(0));
console.log(decToBin(1));
console.log(decToBin(2));
console.log(decToBin(3));
console.log(decToBin(4));
console.log(decToBin(5));
console.log(decToBin(6));

An actual solution that logic can be implemented by any programming language:

If you sure it is positive only:

var a = 0;
var n = 12; // your input
var m = 1;
while(n) {
    a = a + n%2*m;
    n = Math.floor(n/2);
    m = m*10;
}

console.log(n, ':', a) // 12 : 1100

If can negative or positive -

(n >>> 0).toString(2)

I used a different approach to come up with something that does this. I've decided to not use this code in my project, but I thought I'd leave it somewhere relevant in case it is useful for someone.

  • Doesn't use bit-shifting or two's complement coercion.
  • You choose the number of bits that comes out (it checks for valid values of '8', '16', '32', but I suppose you could change that)
  • You choose whether to treat it as a signed or unsigned integer.
  • It will check for range issues given the combination of signed/unsigned and number of bits, though you'll want to improve the error handling.
  • It also has the "reverse" version of the function which converts the bits back to the int. You'll need that since there's probably nothing else that will interpret this output :D

 function intToBitString(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } var min = unsigned ? 0 : - (2 ** size / 2); var limit = unsigned ? 2 ** size : 2 ** size / 2; if (!Number.isInteger(input) || input < min || input >= limit) { throw "out of range or not an int"; } if (!unsigned) { input += limit; } var binary = input.toString(2).replace(/^-/, ''); return binary.padStart(size, '0'); } function bitStringToInt(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } input = parseInt(input, 2); if (!unsigned) { input -= 2 ** size / 2; } return input; } // EXAMPLES var res; console.log("(uint8)10"); res = intToBitString(10, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint8)127"); res = intToBitString(127, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(int8)127"); res = intToBitString(127, 8, false); console.log("intToBitString(res, 8, false)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, false)); console.log("---"); console.log("(int8)-128"); res = intToBitString(-128, 8, false); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint16)5000"); res = intToBitString(5000, 16, true); console.log("intToBitString(res, 16, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 16, true)); console.log("---"); console.log("(uint32)5000"); res = intToBitString(5000, 32, true); console.log("intToBitString(res, 32, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 32, true)); console.log("---");

This is a method that I use. It's a very fast and concise method that works for whole numbers.

If you want, this method also works with BigInts. You just have to change each 1 to 1n .

// Assuming {num} is a whole number
function toBin(num){
    let str = "";
    do {
        str = `${num & 1}${str}`;
        num >>= 1;
    } while(num);
    return str
}

Explanation

This method, in a way, goes through all the bits of the number as if it's already a binary number.

It starts with an empty string, and then it prepends the last bit. num & 1 will return the last bit of the number ( 1 or 0 ). num >>= 1 then removes the last bit and makes the second-to-last bit the new last bit. The process is repeated until all the bits have been read.

Of course, this is an extreme simplification of what's actually going on. But this is how I generalize it.

This is my code:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

This is the solution . Its quite simple as a matter of fact

function binaries(num1){ 
        var str = num1.toString(2)
        return(console.log('The binary form of ' + num1 + ' is: ' + str))
     }
     binaries(3

)

        /*
         According to MDN, Number.prototype.toString() overrides 
         Object.prototype.toString() with the useful distinction that you can 
         pass in a single integer argument. This argument is an optional radix, 
         numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to 
         get a string representation of the binary for the base 10 number 100, 
         i.e. 1100100.
        */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM