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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP