Vấn đề
Chúng ta cần viết một lớp JavaScript có hai phương thức thành viên:
toHex: Nhận chuỗi ASCII và trả về chuỗi hex tương đương.toASCII: Nhận chuỗi hex và trả về chuỗi ASCII tương đương.
Ví dụ, nếu đầu vào là:
Đầu vào
const str = 'this is a string';
Thì hex và ASCII tương ứng là:
74686973206973206120737472696e67 this is a string
Ví dụ
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));
Kết quả
74686973206973206120737472696e67 this is a string