JavaScript 中的 ASCII 到十六进制和十六进制到 ASCII 转换器类
javascriptweb developmentfront end technology
问题
我们需要编写一个具有成员函数 − 的 JavaScript 类
- toHex:它接受一个 ASCII 字符串并返回其十六进制等效值。
- toASCII:它接受一个十六进制字符串并返回其 ASCII 等效值。
例如,如果函数的输入是 −
输入
const str = 'this is a string';
那么相应的十六进制和 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