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
CodePudding user response:
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) " ";
}