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
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话