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