使用自定义映射 JavaScript 将十进制的整数映射到十六进制
通常,当我们将十进制转换为十六进制(基数 16)时,我们使用集合 0123456789ABCDEF 来映射该数字。
我们需要编写一个函数来执行完全相同的功能,但允许用户使用除上述集合以外的任意范围。
例如 −
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
这就是我们需要做的。
因此,我们通过创建一个函数 toHex() 来完成此操作,该函数利用递归从整数构建一个十六进制。准确地说,它将采用四个参数,但在这些参数中,只有前两个参数对最终用户有用。
第一个参数将是转换为十六进制的数字,第二个参数是自定义范围,它将是可选的,如果提供,则应恰好是 16 个字符的字符串,否则函数将返回 false。其他两个参数是 hexString 和 isNegative,它们在默认情况下分别设置为一个空字符串和一个布尔值。
示例
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'))输出
控制台中的输出将为 −
WUS 16B A05
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP