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.