- 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
Map an integer from decimal base to hexadecimal with custom mapping JavaScript
Usually when we convert a decimal to hexadecimal (base 16) we use the set 0123456789ABCDEF to map the number.
We are required to write a function that does exactly the same but provides user the freedom to use any scale rather than the one mentioned above.
For example −
The hexadecimal notation of the decimal 363 is 16B But if the user decides to use, say, a scale ‘qwertyuiopasdfgh’ instead of ‘0123456789ABCDEF’, the number 363, then will be represented by wus
That’s what we are required to do.
So, let’s do this by making a function toHex() that makes use of recursion to build a hex out of the integer. To be precise, it will take in four arguments, but out of those four, only the first two will be of use for the end user.
First of them will be the number to be converted to hex, and second the custom scale, it will be optional and if it is supplied, it should be a string of exactly 16 characters otherwise the function returns false. The other two arguments are hexString and isNegative which are set to empty string and a boolean respectively by default.
Example
const num = 363; const toHex = ( num, hexString = '0123456789ABCDEF', hex = '', isNegative = num < 0 ) => { if(hexString.length !== 16){ return false; } num = Math.abs(num); if(num && typeof num === 'number'){ //recursively append the remainder to hex and divide num by 16 return toHex(Math.floor(num / 16), hexString, `${hexString[num%16]}${hex}`, isNegative); }; return isNegative ? `-${hex}` : hex; }; console.log(toHex(num, 'QWERTYUIOPASDFGH')); console.log(toHex(num)); console.log(toHex(num, 'QAZWSX0123456789'))
Output
The output in the console will be −
WUS 16B A05