sajad torkamani

You want a function that takes two params:

  • num: number to be converted into binary or twos complement.
  • numBits: number of bits used to store num.

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)
}

repl

Sources

Tagged: Snippets

Leave a comment

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