在 JavaScript 中將 ASCII 轉換成十六進位制


我們需要編寫一個 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

更新時間: 11-Dec-2020

762 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.