0

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!

4
  • Why do you need the conversion? Commented Apr 4, 2022 at 13:37
  • Are you sure that the string "0000000000000101", which would be like '\x30\x30...\x30\x31\x30\x31', which consists of [0b110000, 0b110000, ...., 0b110000, 0b110001, 0b110000, 0b110001], is the actual thing required? NodeJS can write actual binary files. ASCII '0' characters are not just 0 bits, and '1' characters are not just 1 bits either Commented Apr 5, 2022 at 12:20
  • @qrsngky you could be right. I how would I do this? Commented Apr 6, 2022 at 13:09
  • 1
    I'm not sure about your requirements, but there are functions designed for that: buf.readUIntLE and but.writeUIntLE for non-negative integers and Buffer.from(...) and buf.toString(...) for strings. Are the integers in your program only from 0 to 65535? Commented Apr 6, 2022 at 14:36

1 Answer 1

1

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) + " ";
  }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.