เราจำเป็นต้องเขียนฟังก์ชัน 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