Reputation: 11
how could I convert a string in binary to string again in react native?
Ex: 01010 to Hello
I have the code to convert string to binary
Ex: text.split('').map(l => l.charCodeAt(0).toString(2)).join(' '),
Upvotes: 0
Views: 1002
Reputation: 674
To convert binary string to sting you can use parseInt
and String.fromCharCode
parseInt
converts strings to number. First argument is string value and the second argument is the base value in which the string representation is.
let num = parseInt(binaryStr, 2);
String.fromCharCode
converts character code to matching string.
let str = String.fromCharCode(65);
Complete code with example:
const text = 'Hello'
let binaryStr = text.split('').map(l => l.charCodeAt(0).toString(2)).join(' ');
console.log('Binary string:', binaryStr);
//To convert binary to string
let strVal = binaryStr.split(' ').map(l => String.fromCharCode(parseInt(l, 2))).join('');
console.log('String:', strVal);
Output of above code:
Binary string: 1001000 1100101 1101100 1101100 1101111
String: Hello
Upvotes: 0
Reputation: 10655
let txt="Hello".split('').map(l => l.charCodeAt(0).toString(2)).join(' ')
let s = txt.split(" ").map(w=> String.fromCharCode(parseInt(w,2)))
console.log(s.join(""))
Just convert binary string back to integer and map those values to character using fromCharCode
Upvotes: 1