pgalle
pgalle

Reputation: 304

How to convert string and integer to binary in nodejs?

I have the following problems. I have an integer and a string. Both of them need to be converted into binary format. For the integer I found a solution that, as far as I can tell, works. The string on the other hand, I don't have a solid understanding of it.

String(16), as far as I understand, means something like Array<UInt8> and has a fixed length of 16. Am I correct? If so, is there a better way to converting them by hand built in in NodeJS?

const myNumber = 2
const myString = 'MyString'

const myNumberInBinary = toUInt16(myNumber) // eg. 0000000000000101
const myStringinBinary = toString16(myString) // I honestly don't know

function toUInt16(number) {
    let binaryString = Number(number).toString(2)
    while (binaryString.length < 16) {
        binaryString = '0' + binaryString
    }
    return binaryString
}

// TODO: implement
function toString16(string) {
    ...
    return binaryString
}

best regards

EDIT: Thanks for all the comments and the answer. They helped me understand this process better. The solution I ended up with is this one:

const bitString = "00000101"
const buffer = new Buffer.alloc(bitString.length / 8)

for (let i = 0; i < bitString.length; i++) {
  const value = bitString.substring(i * 8, (i * 8) + 8)
  buffer[i] = Number(value)        
}

fs.writeFileSync('my_file', buffer, 'binary')

Thanks again!

Upvotes: 0

Views: 1578

Answers (1)

nedoder
nedoder

Reputation: 473

You should loop through the string and do this on each character:

 let result = ""
 
 for (let i = 0; i < myString.length; i++) {
      result += myString[i].charCodeAt(0).toString(2) + " ";
  }

Upvotes: 1

Related Questions