เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้สตริงที่แสดงหมายเลข ASCII ฟังก์ชันควรแปลงตัวเลขเป็นรหัสฐานสิบหกที่สอดคล้องกันและส่งคืนเลขฐานสิบหก
ตัวอย่างเช่น −
f สตริง ASCII อินพุตคือ -
const str = '159';
จากนั้นรหัสฐานสิบหกควรเป็น 313539
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = '159';
const convertToHexa = (str = '') =>{
const res = [];
const { length: len } = str;
for (let n = 0, l = len; n < l; n ++) {
const hex = Number(str.charCodeAt(n)).toString(16);
res.push(hex);
};
return res.join('');
}
console.log(convertToHexa('159')); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
313539