- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ASCII to hex and hex to ASCII converter class in JavaScript
Problem
We are required to write a JavaScript class that have to member functions −
- toHex: It takes in a ASCII string and returns its hexadecimal equivalent.
- toASCII: It takes in a hexadecimal string and returns its ASCII equivalent.
For example, if the input to the function is −
Input
const str = 'this is a string';
Then the respective hex and ascii should be −
74686973206973206120737472696e67 this is a string
Example
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));
Output
74686973206973206120737472696e67 this is a string
Advertisements
To Continue Learning Please Login
Login with Google