

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Convert decimal integer to hexadecimal number in Java
- Java Program to convert decimal integer to hexadecimal number
- JavaScript map value to keys (reverse object mapping)
- Java Program to convert from decimal to hexadecimal
- How to convert decimal to hexadecimal in JavaScript?
- Decrypt String from Alphabet to Integer Mapping in Python
- How to Convert Decimal to Hexadecimal?
- How to Convert Hexadecimal to Decimal?
- C++ program for hexadecimal to decimal
- Reverse mapping an object in JavaScript
- How to convert an integer to a hexadecimal string in Python?
- Hexadecimal integer literal in Java
- How to convert a string of any base to an integer in JavaScript?
- Java Program to convert integer to hexadecimal
- How to convert Decimal to Hexadecimal in Java