ปัญหา
เราจำเป็นต้องเขียนคลาส JavaScript ที่มีฟังก์ชั่นสมาชิก -
- toHex:ใช้สตริง ASCII และส่งกลับค่าเทียบเท่าเลขฐานสิบหก
- toASCII:ใช้สตริงเลขฐานสิบหกและส่งกลับค่าเทียบเท่า ASCII
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ −
ป้อนข้อมูล
const str = 'this is a string';
ดังนั้นเลขฐานสิบหกและ ascii ที่เกี่ยวข้องควรเป็น −
74686973206973206120737472696e67 this is a string
ตัวอย่าง
const str = 'this is a string';
class Converter{
toASCII = (hex = '') => {
const res = [];
for(let i = 0; i < hex.length; i += 2){
res.push(hex.slice(i,i+2));
};
return res
.map(el => String.fromCharCode(parseInt(el, 16)))
.join('');
};
toHex = (ascii = '') => {
return ascii
.split('')
.map(el => el.charCodeAt().toString(16))
.join('');
};
};
const converter = new Converter();
const hex = converter.toHex(str);
console.log(hex);
console.log(converter.toASCII(hex)); ผลลัพธ์
74686973206973206120737472696e67 this is a string