เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่แทนรหัสไบนารี ฟังก์ชันควรคืนค่าการแทนที่ด้วยตัวอักษรของสตริงนั้น
ตัวอย่างเช่น
ถ้าสตริงอินพุทไบนารีคือ
const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100';
ผลลัพธ์ควรเป็น
const output = 'Hello World';
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100';
const binaryToString = (binary = '') => {
let strArr = binary.split(' ');
const str = strArr.map(part=> {
return String.fromCharCode(parseInt(part, 2));
}).join('');
return str;
};
console.log(binaryToString(str));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
Hello World