JavaScript 中的 ASCII 轉十六進位制和十六進位制轉 ASCII 轉換器類


問題

我們要求編寫一個 JavaScript 類,其中包括成員函式 -

  • toHex:它接收一個 ASCII 字串並返回其十六進位制等效值。
  • toASCII:它接收一個十六進位制字串並返回其 ASCII 等效值。

例如,如果函式的輸入 -

輸入

const str = 'this is a string';

那麼相應的 hex 和 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

更新日期: 2021 年 4 月 22 日

635 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.