Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแปลง ASCII เป็นรหัสฐานสิบหก (Hexadecimal) ใน JavaScript

บทความนี้สาธิตฟังก์ชันแปลงสตริงที่เป็นตัวเลข ASCII ให้เป็นรหัสฐานสิบหก (hex) ของแต่ละตัวอักษร

ตัวอย่าง

const str = '159';
// '1' -> 0x31, '5' -> 0x35, '9' -> 0x39
// ผลลัพธ์: '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

คำอธิบาย

ใช้ charCodeAt() หา Unicode code point (สำหรับ ASCII เท่ากับค่า ASCII) แล้ว toString(16) แปลงเป็นฐานสิบหก

รวมผลลัพธ์ด้วย join('')