Convert number to standard binary or twos complement
17 April 2022 (Updated 17 May 2022)
You want a function that takes two params:
num
: number to be converted into binary or twos complement.numBits
: number of bits used to storenum
.
and returns a standard binary representation if num
is positive or two’s complement representation if num
is negative:
twosComplement(3, 32) // 11
twosComplement(-3, 32) // 11111111111111111111111111111101
twosComplement(4, 8) // 100
twosComplement(-4, 8) // 11111100
Here’s how:
function toBinary(num, numBits) {
const binary = num.toString(2).replace('-', '')
if (num >= 0) {
return binary
}
const numBitsToPrepend = numBits - binary.length
const longBinary = '0'.repeat(numBitsToPrepend) + binary
const smallestNonZeroBitIndex = longBinary.lastIndexOf('1')
const invertedBits = longBinary
.slice(0, smallestNonZeroBitIndex)
.split('')
.map(bit => bit === '1' ? '0': '1')
.join('')
return invertedBits + longBinary.slice(smallestNonZeroBitIndex)
}
Sources
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment