How to convert text to binary code in JavaScript?

后端 未结 13 1720
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in "TEST

相关标签:
13条回答
  • 2020-11-28 05:43

    Provided you're working in node or a browser with BigInt support, this version cuts costs by saving the expensive string construction for the very end:

    const zero = 0n
    const shift = 8n
    
    function asciiToBinary (str) {
      const len = str.length
      let n = zero
      for (let i = 0; i < len; i++) {
        n = (n << shift) + BigInt(str.charCodeAt(i))
      }
      return n.toString(2).padStart(len * 8, 0)
    }
    

    It's about twice as fast as the other solutions mentioned here including this simple es6+ implementation:

    const toBinary = s => [...s]
      .map(x => x
        .codePointAt()
        .toString(2)
        .padStart(8,0)
      )
      .join('')
    

    If you need to handle unicode characters, here's this guy:

    const zero = 0n
    const shift = 8n
    const bigShift = 16n
    const byte = 255n
    
    function unicodeToBinary (str) {
      const len = str.length
      let n = zero
      for (let i = 0; i < len; i++) {
        const bits = BigInt(str.codePointAt(i))
        n = (n << (bits > byte ? bigShift : shift)) + bits
      }
      const bin = n.toString(2)
      return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
    }
    
    0 讨论(0)
提交回复
热议问题