如何在JavaScript中将十进制值转换为十六进制值?


当前回答

function toHex(d) {
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}

其他回答

function dec2hex(i)
{
  var result = "0000";
  if      (i >= 0    && i <= 15)    { result = "000" + i.toString(16); }
  else if (i >= 16   && i <= 255)   { result = "00"  + i.toString(16); }
  else if (i >= 256  && i <= 4095)  { result = "0"   + i.toString(16); }
  else if (i >= 4096 && i <= 65535) { result =         i.toString(16); }
  return result
}

这是基于Prestaul和Tod的解决方案。然而,这是一个概括,它解释了变量的不同大小(例如,解析来自微控制器串行日志的有符号值)。

function decimalToPaddedHexString(number, bitsize)
{ 
  let byteCount = Math.ceil(bitsize/8);
  let maxBinValue = Math.pow(2, bitsize)-1;

  /* In node.js this function fails for bitsize above 32bits */
  if (bitsize > 32)
    throw "number above maximum value";

  /* Conversion to unsigned form based on  */
  if (number < 0)
    number = maxBinValue + number + 1;

  return "0x"+(number >>> 0).toString(16).toUpperCase().padStart(byteCount*2, '0');
}

测试脚本:

for (let n = 0 ; n < 64 ; n++ ) { 
     let s=decimalToPaddedHexString(-1, n); 
     console.log(`decimalToPaddedHexString(-1,${(n+"").padStart(2)}) = ${s.padStart(10)} = ${("0b"+parseInt(s).toString(2)).padStart(34)}`);
   }

测试结果:

decimalToPaddedHexString(-1, 0) =        0x0 =                                0b0
decimalToPaddedHexString(-1, 1) =       0x01 =                                0b1
decimalToPaddedHexString(-1, 2) =       0x03 =                               0b11
decimalToPaddedHexString(-1, 3) =       0x07 =                              0b111
decimalToPaddedHexString(-1, 4) =       0x0F =                             0b1111
decimalToPaddedHexString(-1, 5) =       0x1F =                            0b11111
decimalToPaddedHexString(-1, 6) =       0x3F =                           0b111111
decimalToPaddedHexString(-1, 7) =       0x7F =                          0b1111111
decimalToPaddedHexString(-1, 8) =       0xFF =                         0b11111111
decimalToPaddedHexString(-1, 9) =     0x01FF =                        0b111111111
decimalToPaddedHexString(-1,10) =     0x03FF =                       0b1111111111
decimalToPaddedHexString(-1,11) =     0x07FF =                      0b11111111111
decimalToPaddedHexString(-1,12) =     0x0FFF =                     0b111111111111
decimalToPaddedHexString(-1,13) =     0x1FFF =                    0b1111111111111
decimalToPaddedHexString(-1,14) =     0x3FFF =                   0b11111111111111
decimalToPaddedHexString(-1,15) =     0x7FFF =                  0b111111111111111
decimalToPaddedHexString(-1,16) =     0xFFFF =                 0b1111111111111111
decimalToPaddedHexString(-1,17) =   0x01FFFF =                0b11111111111111111
decimalToPaddedHexString(-1,18) =   0x03FFFF =               0b111111111111111111
decimalToPaddedHexString(-1,19) =   0x07FFFF =              0b1111111111111111111
decimalToPaddedHexString(-1,20) =   0x0FFFFF =             0b11111111111111111111
decimalToPaddedHexString(-1,21) =   0x1FFFFF =            0b111111111111111111111
decimalToPaddedHexString(-1,22) =   0x3FFFFF =           0b1111111111111111111111
decimalToPaddedHexString(-1,23) =   0x7FFFFF =          0b11111111111111111111111
decimalToPaddedHexString(-1,24) =   0xFFFFFF =         0b111111111111111111111111
decimalToPaddedHexString(-1,25) = 0x01FFFFFF =        0b1111111111111111111111111
decimalToPaddedHexString(-1,26) = 0x03FFFFFF =       0b11111111111111111111111111
decimalToPaddedHexString(-1,27) = 0x07FFFFFF =      0b111111111111111111111111111
decimalToPaddedHexString(-1,28) = 0x0FFFFFFF =     0b1111111111111111111111111111
decimalToPaddedHexString(-1,29) = 0x1FFFFFFF =    0b11111111111111111111111111111
decimalToPaddedHexString(-1,30) = 0x3FFFFFFF =   0b111111111111111111111111111111
decimalToPaddedHexString(-1,31) = 0x7FFFFFFF =  0b1111111111111111111111111111111
decimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111
Thrown: 'number above maximum value'

注意:不太确定为什么它在32位以上失败

任意精度

此解决方案接受输入的十进制字符串,并返回十六进制字符串。支持小数。算法

将数字拆分为符号(s)、整数部分(i)和小数部分(f),例如,对于-123.75,我们得到s=真,i=123,f=75整数部分到十六进制:如果i='0'停止取模:m=i%16(任意精度)将m转换为十六进制数字并放入结果字符串对于下一步,计算整数部分i=i/16(任意精度)小数部分计数小数n乘以k=f*16(任意精度)将k拆分为n个数字的右侧部分并将其置于f,将其余数字的左侧部分拆分为d将d转换为十六进制并添加到结果中。当结果小数位数足够时完成

//@param decStr-非负整数字符串//@param除数-正整数函数dec2Hex任意(decStr,fracDigits=0){//Helper:将任意精度数除以js数//@param decStr-非负整数字符串//@param除数-正整数函数arbDivision(decStr,除数){ //算法https://www.geeksforgeeks.org/divide-large-number-represented-string/让ans=“”;设idx=0;设temp=+decStr[idx];而(temp<除数)temp=temp*10++decStr[++idx];而(decStr.length>idx){ans+=(温度/除数)|0;temp=(temp%除数)*10++decStr[++idx];} 如果(ans.length==0)返回“0”;返回ans;} //Helper:任意精度数的计算模块//@param decStr-非负整数字符串//@param mod-正整数函数arbMod(decStr,mod){//算法https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/设res=0;for(设i=0;i<decStr.length;i++)res=(res*10++decStr[i])%模;回报率;} //Helper:将任意精度整数乘以js数//@param decStr-非负整数字符串//@param mult-正整数函数arbMultiply(decStr,mult){设r=“”;设m=0;对于(设i=decStr.length-1;i>=0;i-){设n=m+mult*(+decStr[i]);r=(i?n%10:n)+rm=n/10|0;}返回r;}//dec2hex算法从这里开始设h=“0123456789abcdef”;//十六进制字母表设m=decStr.match(/-?(.*?)\.(.*)?/)||decStr.匹配(/-?(.*)/);//分离符号,整数,分数设i=m[1]。替换(/^0+/,“”)。替换(/^$/,“0”);//整数部分(无符号和前导零)设f=(m[2]||'0').replace(/0+$/,'').replace(/^$/,'0');//小数部分(不带最后零)设s=decStr[0]=='-';//签名让r=“”;//后果如果(i=='0')r='0';while(i!='0'){//整数部分r=h[arbMod(i,16)]+r;i=arb除法(i,16);}如果(fracDigits)r+=“.”;设n=f.length;对于(设j=0;j<fracDigits;j++){//frac部分设k=arbMultiply(f,16);f=k切片(-n);设d=k.slice(0,k.length-n);r+=d长度?h[+d]:“0”;}return(s?'-':'')+r;}// -----------//测试// -----------让测试=[["0",2],["000",2], ["123",0],["-123",0], ["00.000",2],["255.75",5],["-255.75",5], ["127.999",32], ];console.log('输入标准能力');test.forEach(t=>{让nonArb=(+t[0]).toString(16).padEnd(17,'');设arb=dec2Hex任意(t[0],t[1]);console.log(t[0].padEnd(10,''),nonArb,arb);});//长示例(点后40位)例如=“123456789012345678901234567890.09876543210987654321”console.log(`\nLong示例:`);console.log('dec:',示例);console.log('hex:',dec2Hex任意(例如,40));

如果要转换大整数,即大于Number.MAX_SAFE_INTEGER--9007199254740991的数字,则可以使用以下代码

const-hugeNumber=“9007199254740991873839”//确保其在字符串中const hexOfHugeNumber=BigInt(hugeNumber).toString(16);console.log(hexOfHugeNumber)

var number = 3200;
var hexString = number.toString(16);

16是基数,十六进制数中有16个值:-)