Categories
JavaScript Answers

How to Convert Negative Numbers to a Binary String in JavaScript?

Spread the love

Sometimes, we want to convert negative numbers to a binary string in JavaScript.

In this article, we’ll look at how to convert negative numbers to a binary string in JavaScript.

Convert Negative Numbers to a Binary String in JavaScript

To convert negative numbers to a binary string in JavaScript, we can use the toString method or a zero-fill right shift to convert negative numbers to binary strings.

For instance, we can write:

const str = (-3).toString(2);  
console.log(str)

to convert -3 to '-11' .

The negative sign is preserved with this conversion.

To use the bit shift operation to convert a negative number to a binary string, we write:

const str = (-3 >>> 0).toString(2);  
console.log(str)

Then str is '11111111111111111111111111111101' , which is the unsigned 32-bit integer version of the decimal number -3.

Conclusion

To convert negative numbers to a binary string in JavaScript, we can use the toString method or a zero-fill right shift to convert negative numbers to binary strings.

Leave a Reply

Your email address will not be published. Required fields are marked *