JavaScript 中的 ASCII 到十六进制和十六进制到 ASCII 转换器类
问题
我们被要求写有成员函数的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