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

发布于 2024-07-05 19:46:43 字数 40 浏览 10 评论 0原文

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

How do you convert decimal values to their hexadecimal equivalent in JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

潦草背影 2024-07-12 19:46:44

任意精度

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

  • 将数字拆分为符号 (s)、整数部分 (i) 和小数部分 (f),例如 -123.75 我们有 s=truei=123f=75
  • 整数部分到十六进制:
    • 如果i='0'停止
    • 获取模数:m=i%16(任意精度)
    • m 转换为十六进制数字并放入结果字符串
    • 下一步计算整数部分i=i/16(任意精度)
  • 整数部分 i=i/16 (任意精度)小数部分
    • 计算小数位n
    • 乘以k=f*16(任意精度)
    • k拆分为右侧的n位数字,并将它们放入f,将左侧的部分与其余数字拆分,并将它们放入<代码>d
    • d 转换为十六进制并添加到结果中。
    • 当结果小数位数足够时结束
// @param decStr - string with non-negative integer
// @param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {   
    // Helper: divide arbitrary precision number by js number
    // @param decStr - string with non-negative integer
    // @param divisor - positive integer
    function arbDivision(decStr, divisor) 
    { 
        // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
        let ans=''; 
        let idx = 0; 
        let temp = +decStr[idx]; 
        while (temp < divisor) temp = temp * 10 + +decStr[++idx]; 

        while (decStr.length > idx) { 
            ans += (temp / divisor)|0 ; 
            temp = (temp % divisor) * 10 + +decStr[++idx]; 
        } 

        if (ans.length == 0) return "0"; 

        return ans; 
    } 

    // Helper: calc module of arbitrary precision number
    // @param decStr - string with non-negative integer
    // @param mod - positive integer
    function arbMod(decStr, mod) { 
      // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
      let res = 0; 

      for (let i = 0; i < decStr.length; i++) 
        res = (res * 10 + +decStr[i]) % mod; 

      return res; 
    } 

    // Helper: multiply arbitrary precision integer by js number
    // @param decStr - string with non-negative integer
    // @param mult - positive integer
    function arbMultiply(decStr, mult) {
      let r='';
      let m=0;
      for (let i = decStr.length-1; i >=0 ; i--) {
        let n = m+mult*(+decStr[i]);
        r= (i ? n%10 : n) + r 
        m= n/10|0;
      }
      return r;
    }
    
    
    // dec2hex algorithm starts here
    
    let h= '0123456789abcdef';                                         // hex 'alphabet'
    let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/);   // separate sign,integer,ractional
    let i= m[1].replace(/^0+/,'').replace(/^$/,'0');                   // integer part (without sign and leading zeros)
    let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0');            // fractional part (without last zeros)
    let s= decStr[0]=='-';                                                                             // sign

    let r='';                                                                                                          // result
    
    if(i=='0') r='0';
        
    while(i!='0') {                                                    // integer part
      r=h[arbMod(i,16)]+r; 
      i=arbDivision(i,16);
    }
            
    if(fracDigits) r+=".";
        
    let n = f.length;
    
    for(let j=0; j<fracDigits; j++) {                                  // frac part
      let k= arbMultiply(f,16);
      f = k.slice(-n);
      let d= k.slice(0,k.length-n); 
      r+= d.length ? h[+d] : '0';
    }
            
    return (s?'-':'')+r;
}








// -----------
// TESTS
// -----------



let tests = [
  ["0",2],
  ["000",2],  
  ["123",0],
  ["-123",0],  
  ["00.000",2],
  
  ["255.75",5],
  ["-255.75",5], 
  ["127.999",32], 
];

console.log('Input      Standard          Abitrary');
tests.forEach(t=> {
  let nonArb = (+t[0]).toString(16).padEnd(17,' ');
  let arb = dec2HexArbitrary(t[0],t[1]);
  console.log(t[0].padEnd(10,' '), nonArb, arb); 
});


// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex:     ',dec2HexArbitrary(example,40));

Arbitrary precision

This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm

  • split number to sign (s), integer part (i) and fractional part (f) e.g for -123.75 we have s=true, i=123, f=75
  • integer part to hex:
    • if i='0' stop
    • get modulo: m=i%16 (in arbitrary precision)
    • convert m to hex digit and put to result string
    • for next step calc integer part i=i/16 (in arbitrary precision)
  • fractional part
    • count fractional digits n
    • multiply k=f*16 (in arbitrary precision)
    • split k to right part with n digits and put them to f, and left part with rest of digits and put them to d
    • convert d to hex and add to result.
    • finish when number of result fractional digits is enough

// @param decStr - string with non-negative integer
// @param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {   
    // Helper: divide arbitrary precision number by js number
    // @param decStr - string with non-negative integer
    // @param divisor - positive integer
    function arbDivision(decStr, divisor) 
    { 
        // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
        let ans=''; 
        let idx = 0; 
        let temp = +decStr[idx]; 
        while (temp < divisor) temp = temp * 10 + +decStr[++idx]; 

        while (decStr.length > idx) { 
            ans += (temp / divisor)|0 ; 
            temp = (temp % divisor) * 10 + +decStr[++idx]; 
        } 

        if (ans.length == 0) return "0"; 

        return ans; 
    } 

    // Helper: calc module of arbitrary precision number
    // @param decStr - string with non-negative integer
    // @param mod - positive integer
    function arbMod(decStr, mod) { 
      // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
      let res = 0; 

      for (let i = 0; i < decStr.length; i++) 
        res = (res * 10 + +decStr[i]) % mod; 

      return res; 
    } 

    // Helper: multiply arbitrary precision integer by js number
    // @param decStr - string with non-negative integer
    // @param mult - positive integer
    function arbMultiply(decStr, mult) {
      let r='';
      let m=0;
      for (let i = decStr.length-1; i >=0 ; i--) {
        let n = m+mult*(+decStr[i]);
        r= (i ? n%10 : n) + r 
        m= n/10|0;
      }
      return r;
    }
    
    
    // dec2hex algorithm starts here
    
    let h= '0123456789abcdef';                                         // hex 'alphabet'
    let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/);   // separate sign,integer,ractional
    let i= m[1].replace(/^0+/,'').replace(/^$/,'0');                   // integer part (without sign and leading zeros)
    let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0');            // fractional part (without last zeros)
    let s= decStr[0]=='-';                                                                             // sign

    let r='';                                                                                                          // result
    
    if(i=='0') r='0';
        
    while(i!='0') {                                                    // integer part
      r=h[arbMod(i,16)]+r; 
      i=arbDivision(i,16);
    }
            
    if(fracDigits) r+=".";
        
    let n = f.length;
    
    for(let j=0; j<fracDigits; j++) {                                  // frac part
      let k= arbMultiply(f,16);
      f = k.slice(-n);
      let d= k.slice(0,k.length-n); 
      r+= d.length ? h[+d] : '0';
    }
            
    return (s?'-':'')+r;
}








// -----------
// TESTS
// -----------



let tests = [
  ["0",2],
  ["000",2],  
  ["123",0],
  ["-123",0],  
  ["00.000",2],
  
  ["255.75",5],
  ["-255.75",5], 
  ["127.999",32], 
];

console.log('Input      Standard          Abitrary');
tests.forEach(t=> {
  let nonArb = (+t[0]).toString(16).padEnd(17,' ');
  let arb = dec2HexArbitrary(t[0],t[1]);
  console.log(t[0].padEnd(10,' '), nonArb, arb); 
});


// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex:     ',dec2HexArbitrary(example,40));

余厌 2024-07-12 19:46:44

下面的代码将十进制值 d 转换为十六进制。 它还允许您向十六进制结果添加填充。 所以0默认会变成00。

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}

The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}
这样的小城市 2024-07-12 19:46:44

AFAIK 评论 57807 是错误的,应该是就像是:
var hex = Number(d).toString(16);
代替
var hex = parseInt(d, 16);

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}

AFAIK comment 57807 is wrong and should be something like:
var hex = Number(d).toString(16);
instead of
var hex = parseInt(d, 16);

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}
椒妓 2024-07-12 19:46:44

正如接受的答案所述,从十进制转换为十六进制的最简单方法是 var hex = dec.toString(16) 。 但是,您可能更愿意添加字符串转换,因为它可以确保 "12".toString(16) 等字符串表示形式正常工作。

// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);

要反转该过程,您还可以使用下面的解决方案,因为它更短。

var dec = +("0x" + hex);

它在 Google Chrome 和 Firefox 中似乎较慢,但在 Opera 中明显更快。 请参阅http://jsperf.com/hex-to-dec

As the accepted answer states, the easiest way to convert from decimal to hexadecimal is var hex = dec.toString(16). However, you may prefer to add a string conversion, as it ensures that string representations like "12".toString(16) work correctly.

// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);

To reverse the process you may also use the solution below, as it is even shorter.

var dec = +("0x" + hex);

It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.

我家小可爱 2024-07-12 19:46:44

我正在一个相当大的循环中进行十六进制字符串的转换,因此我尝试了多种技术来找到最快的技术。 我的要求是得到一个固定长度的字符串作为结果,并正确编码负值(-1 => ff..f)。

简单的 .toString(16) 对我来说不起作用,因为我需要正确编码负值。 以下代码是迄今为止我在 1-2 字节值上测试过的最快的代码(请注意,symbols 定义了您想要获取的输出符号的数量,即对于 4 字节整数,它应该是等于 8):

var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
    var result = '';
    while (symbols--) {
        result = hex[num & 0xF] + result;
        num >>= 4;
    }
    return result;
}

它在 1-2 字节数字上比 .toString(16) 执行得更快,在更大的数字上执行得更慢(当 symbols >= 6 时),但仍然应该优于正确编码负值的方法。

I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).

Simple .toString(16) didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that symbols defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):

var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
    var result = '';
    while (symbols--) {
        result = hex[num & 0xF] + result;
        num >>= 4;
    }
    return result;
}

It performs faster than .toString(16) on 1-2 byte numbers and slower on larger numbers (when symbols >= 6), but still should outperform methods that encode negative values properly.

森林散布 2024-07-12 19:46:44

您可以在 ECMAScript 6 中执行类似的操作:

const toHex = num => (num).toString(16).toUpperCase();

You can do something like this in ECMAScript 6:

const toHex = num => (num).toString(16).toUpperCase();
囍笑 2024-07-12 19:46:44

如果您正在寻找转换大整数,即大于 Number.MAX_SAFE_INTEGER -- 9007199254740991 的数字,那么您可以使用以下代码

const hugeNumber = "9007199254740991873839" // Make sure its in String
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
console.log(hexOfHugeNumber)

If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code

const hugeNumber = "9007199254740991873839" // Make sure its in String
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
console.log(hexOfHugeNumber)

猫性小仙女 2024-07-12 19:46:44

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

我无法找到一个非常干净/简单的十进制到十六进制的转换,并且不涉及一堆函数和数组......所以我不得不做这是给我自己的。

function DecToHex(decimal) { // Data (decimal)

    length = -1;    // Base string length
    string = '';    // Source 'string'

    characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array

    do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift

        string += characters[decimal & 0xF];   // Mask byte, get that character
        ++length;                              // Increment to length of string

    } while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0

    decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'

    do
        decimal += string[length];
    while (length--); // Flip string forwards, with the prefixed '0x'

    return (decimal); // return (hexadecimal);
}

/* Original: */

D = 3678;    // Data (decimal)
C = 0xF;    // Check
A = D;        // Accumulate
B = -1;        // Base string length
S = '';        // Source 'string'
H = '0x';    // Destination 'string'

do {
    ++B;
    A& = C;

    switch(A) {
        case 0xA: A='A'
        break;

        case 0xB: A='B'
        break;

        case 0xC: A='C'
        break;

        case 0xD: A='D'
        break;

        case 0xE: A='E'
        break;

        case 0xF: A='F'
        break;

        A = (A);
    }
    S += A;

    D >>>= 0x04;
    A = D;
} while(D)

do
    H += S[B];
while (B--)

S = B = A = C = D; // Zero out variables
alert(H);    // H: holds hexadecimal equivalent

How to convert decimal to hexadecimal in JavaScript

I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.

function DecToHex(decimal) { // Data (decimal)

    length = -1;    // Base string length
    string = '';    // Source 'string'

    characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array

    do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift

        string += characters[decimal & 0xF];   // Mask byte, get that character
        ++length;                              // Increment to length of string

    } while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0

    decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'

    do
        decimal += string[length];
    while (length--); // Flip string forwards, with the prefixed '0x'

    return (decimal); // return (hexadecimal);
}

/* Original: */

D = 3678;    // Data (decimal)
C = 0xF;    // Check
A = D;        // Accumulate
B = -1;        // Base string length
S = '';        // Source 'string'
H = '0x';    // Destination 'string'

do {
    ++B;
    A& = C;

    switch(A) {
        case 0xA: A='A'
        break;

        case 0xB: A='B'
        break;

        case 0xC: A='C'
        break;

        case 0xD: A='D'
        break;

        case 0xE: A='E'
        break;

        case 0xF: A='F'
        break;

        A = (A);
    }
    S += A;

    D >>>= 0x04;
    A = D;
} while(D)

do
    H += S[B];
while (B--)

S = B = A = C = D; // Zero out variables
alert(H);    // H: holds hexadecimal equivalent
誰ツ都不明白 2024-07-12 19:46:44

这是基于 Prestaul 和 Tod's 的解决方案。 然而,这是一个概括,说明了变量大小的变化(例如,从微控制器串行日志中解析有符号值)。

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 位以上失败

This is based on Prestaul and Tod's solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log).

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');
}

Test script:

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)}`);
   }

Test results:

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'

Note: Not too sure why it fails above 32 bitsize

不可一世的女人 2024-07-12 19:46:44

我还没有找到一个明确的答案,没有检查它是负数还是正数,它使用二进制补码(包括负数)。 为此,我展示了针对一个字节的解决方案:

((0xFF + number +1) & 0x0FF).toString(16);

您可以将此指令用于任意数量的字节,只需在相应的位置添加 FF 即可。 例如,到两个字节:

((0xFFFF + number +1) & 0x0FFFF).toString(16);

如果要将数组整数转换为十六进制字符串:

s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
    s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}

I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:

((0xFF + number +1) & 0x0FF).toString(16);

You can use this instruction to any number bytes, only you add FF in respective places. For example, to two bytes:

((0xFFFF + number +1) & 0x0FFFF).toString(16);

If you want cast an array integer to string hexadecimal:

s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
    s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
缺⑴份安定 2024-07-12 19:46:44

总结一下;

function toHex(i, pad) {

  if (typeof(pad) === 'undefined' || pad === null) {
    pad = 2;
  } 

  var strToParse = i.toString(16);

  while (strToParse.length < pad) {
    strToParse = "0" + strToParse;
  }

  var finalVal =  parseInt(strToParse, 16);

  if ( finalVal < 0 ) {
    finalVal = 0xFFFFFFFF + finalVal + 1;
  }

  return finalVal;
}

但是,如果您不需要在末尾将其转换回整数(即颜色),那么只需确保这些值不是负数就足够了。

To sum it all up;

function toHex(i, pad) {

  if (typeof(pad) === 'undefined' || pad === null) {
    pad = 2;
  } 

  var strToParse = i.toString(16);

  while (strToParse.length < pad) {
    strToParse = "0" + strToParse;
  }

  var finalVal =  parseInt(strToParse, 16);

  if ( finalVal < 0 ) {
    finalVal = 0xFFFFFFFF + finalVal + 1;
  }

  return finalVal;
}

However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.

南风起 2024-07-12 19:46:44
  • rgb(255, 255, 255) // 返回 FFFFFF

  • rgb(255, 255, 300) // 返回 FFFFFF

  • rgb(0,0,0) // 返回 000000

  • rgb(148, 0, 211) // 返回 9400D3

     函数 rgb(...values){ 
                返回值.reduce((acc, cur) => { 
                  让 val = cur >= 255 ?   'ff' : cur <= 0 ?   '00' : 数字(cur).toString(16); 
                  return acc + (val.length === 1 ? '0'+val : val); 
                }, '').toUpperCase(); 
            } 
      
  • rgb(255, 255, 255) // returns FFFFFF

  • rgb(255, 255, 300) // returns FFFFFF

  • rgb(0,0,0) // returns 000000

  • rgb(148, 0, 211) // returns 9400D3

     function rgb(...values){
              return values.reduce((acc, cur) => {
                let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
                return acc + (val.length === 1 ? '0'+val : val);
              }, '').toUpperCase();
          }
    
懵少女 2024-07-12 19:46:44

如果您希望转换为“完整”JavaScript 或 CSS 表示形式,您可以使用以下内容:

  numToHex = function(num) {
    var r=((0xff0000&num)>>16).toString(16),
        g=((0x00ff00&num)>>8).toString(16),
        b=(0x0000ff&num).toString(16);
    if (r.length==1) { r = '0'+r; }
    if (g.length==1) { g = '0'+g; }
    if (b.length==1) { b = '0'+b; }
    return '0x'+r+g+b;                 // ('#' instead of'0x' for CSS)
  };

  var dec = 5974678;
  console.log( numToHex(dec) );        // 0x5b2a96

In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:

  numToHex = function(num) {
    var r=((0xff0000&num)>>16).toString(16),
        g=((0x00ff00&num)>>8).toString(16),
        b=(0x0000ff&num).toString(16);
    if (r.length==1) { r = '0'+r; }
    if (g.length==1) { g = '0'+g; }
    if (b.length==1) { b = '0'+b; }
    return '0x'+r+g+b;                 // ('#' instead of'0x' for CSS)
  };

  var dec = 5974678;
  console.log( numToHex(dec) );        // 0x5b2a96
新人笑 2024-07-12 19:46:44

问题基本上是期望有多少个填充零。

如果您希望数字 1 和 17 中包含字符串 0111。最好使用 Buffer 作为桥梁,将数字转换为字节,然后十六进制只是它的输出格式。 并且字节组织由 Buffer 函数很好地控制,例如 writeUInt32BEwriteInt16LE, ETC。

import { Buffer } from 'buffer';

function toHex(n) { // 4byte
  const buff = Buffer.alloc(4);
  buff.writeInt32BE(n);
  return buff.toString('hex');
}

> toHex(1)
'00000001'
> toHex(17)
'00000011'
> toHex(-1)
'ffffffff'
> toHex(-1212)
'fffffb44'
> toHex(1212)
'000004bc'

The problem basically how many padding zeros to expect.

If you expect string 01 and 11 from Number 1 and 17. it's better to use Buffer as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like writeUInt32BE, writeInt16LE, etc.

import { Buffer } from 'buffer';

function toHex(n) { // 4byte
  const buff = Buffer.alloc(4);
  buff.writeInt32BE(n);
  return buff.toString('hex');
}

> toHex(1)
'00000001'
> toHex(17)
'00000011'
> toHex(-1)
'ffffffff'
> toHex(-1212)
'fffffb44'
> toHex(1212)
'000004bc'
抚笙 2024-07-12 19:46:44

这是我的解决方案:

hex = function(number) {
  return '0x' + Math.abs(number).toString(16);
}

问题是:“如何在 JavaScript 中将十进制转换为十六进制”。 虽然问题没有指定十六进制字符串应以 0x 前缀开头,但任何编写代码的人都应该知道,在十六进制代码中添加 0x 是为了区分十六进制代码编程标识符 em> 和其他数字(1234 可以是十六进制、十进制,甚至八进制)。

因此,要正确回答这个问题,为了编写脚本,必须添加0x前缀。

Math.abs(N) 函数将负数转换为正数,而且作为奖励,它看起来不像有人通过木材削片机运行它。

我想要的答案应该有一个字段宽度说明符,因此我们可以以十六进制编辑应用程序中列出的方式显示 8/16/32/64 位值。 这就是实际的、正确的答案。

Here's my solution:

hex = function(number) {
  return '0x' + Math.abs(number).toString(16);
}

The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).

Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.

The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.

The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.

萌吟 2024-07-12 19:46:44
function toHex(d) {
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
function toHex(d) {
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
羞稚 2024-07-12 19:46:44

为了完整起见,如果您想要二的补码负数的十六进制表示,您可以使用 零填充右移 >>> 运算符。 例如:

> (-1).toString(16)
"-1"

> ((-2)>>>0).toString(16)
"fffffffe"

但是有一个限制: JavaScript 按位运算符将其操作数视为 32 位序列,也就是说,您将获得 32 位二进制补码。

For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift >>> operator. For instance:

> (-1).toString(16)
"-1"

> ((-2)>>>0).toString(16)
"fffffffe"

There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.

厌味 2024-07-12 19:46:44

接受的答案没有考虑单个数字返回的十六进制代码。 这很容易通过以下方式进行调整:

function numHex(s)
{
    var a = s.toString(16);
    if ((a.length % 2) > 0) {
        a = "0" + a;
    }
    return a;
}

并且

function strHex(s)
{
    var a = "";
    for (var i=0; i<s.length; i++) {
        a = a + numHex(s.charCodeAt(i));
    }

    return a;
}

我相信上述答案已被其他人以一种或另一种形式发布过多次。 我将它们包装在 toHex() 函数中,如下所示:

function toHex(s)
{
    var re = new RegExp(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/);

    if (re.test(s)) {
        return '#' + strHex( s.toString());
    }
    else {
        return 'A' + strHex(s);
    }
}

请注意,数字正则表达式来自 10 多个有用的 JavaScript 正则表达式函数可提高您的 Web 应用程序效率

更新:经过多次测试后,我发现了一个错误(正则表达式中的双引号),所以我修复了这个错误。 然而! 经过相当多的测试并阅读了 almaz 的帖子 - 我意识到我无法让负数起作用。

此外 - 我对此进行了一些阅读,因为无论如何,所有 JavaScript 数字都存储为 64 位字 - 我尝试修改 numHex 代码以获取 64 位字。 但事实证明你不能那样做。 如果您将“3.14159265”作为数字放入变量中 - 您将能够得到的只是“3”,因为小数部分只能通过将数字重复乘以十(即:10.0)来访问。 或者换句话说 - 0xF 的十六进制值会导致浮点值在进行 AND 运算之前被转换为整数,从而删除一切都落后于时代。 而不是将值作为一个整体(即:3.14159265)并将浮点值与 0xF 值进行“与”运算。

因此,在这种情况下,最好的办法是将 3.14159265 转换为 字符串,然后只转换该字符串。 由于上述原因,它也使得负数转换变得很容易,因为减号正好变成值前面的 0x26。

所以我所做的就是确定变量包含一个数字 - 只需将其转换为字符串并转换该字符串。 这对每个人来说意味着在服务器端您需要对传入的字符串进行十六进制处理,然后确定传入的信息是数字。 只需在数字前面添加“#”,在返回的字符串前面添加“A”,即可轻松完成此操作。 请参阅 toHex() 函数。

玩得开心!

经过一年的大量思考,我决定“toHex”函数(我也有一个“fromHex”函数)确实需要修改。 整个问题是“我怎样才能更有效地做到这一点?” 我决定 to/from 十六进制函数不应该关心某些内容是否是小数部分,但同时它应该确保小数部分包含在字符串中。

那么问题就变成了“你怎么知道你正在使用十六进制字符串?”。 答案很简单。 使用世界范围内已经认可的标准预串信息。

换句话说 - 使用“0x”。 所以现在我的 toHex 函数会查看它是否已经存在,如果存在 - 它只返回发送给它的字符串。 否则,它会转换字符串、数字等。 这是修改后的 toHex 函数:

/////////////////////////////////////////////////////////////////////////////
//  toHex().  Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
    var l = "0123456789ABCDEF";
    var o = "";

    if (typeof s != "string") {
        s = s.toString();
    }

    if (s.substr(0,2).toLowerCase() == "0x") {
        return s;
    }

    for (var i=0; i<s.length; i++) {
        var c = s.charCodeAt(i);

        o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
    }

    return "0x" + o;
}

这是一个非常快的函数,它考虑了个位数、浮点数,甚至检查该人是否正在发送十六进制值以再次进行十六进制处理。 它仅使用四个函数调用,并且其中只有两个在循环中。 要取消使用的值的十六进制:

/////////////////////////////////////////////////////////////////////////////
//  fromHex().  Convert a hex string to ASCII text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
    var start = 0;
    var o = "";

    if (typeof s != "string") {
        s = s.toString();
    }

    if (s.substr(0,2).toLowerCase() == "0x") {
        start = 2;
    }

    for (var i=start; i<s.length; i+=2) {
        var c = s.substr(i, 2);

        o = o + String.fromCharCode(parseInt(c, 16));
    }

    return o;
}

与 toHex() 函数一样,fromHex() 函数首先查找“0x”,然后将传入的信息转换为字符串(如果它还不是字符串)。 我不知道它怎么不会是一个字符串 - 但以防万一 - 我检查一下。 然后该函数会执行,抓取两个字符并将它们转换为 ASCII 字符。 如果您希望它转换 Unicode,则需要将循环更改为一次转换四 (4) 个字符。 但是您还需要确保该字符串不能被四整除。 如果是 - 那么它是一个标准的十六进制字符串。 (请记住该字符串前面有“0x”。)

一个简单的测试脚本,用于显示 -3.14159265 在转换为字符串时仍然是 -3.14159265。

<?php

    echo <<<EOD
<html>
    <head><title>Test</title>
        <script>
            var a = -3.14159265;
            alert( "A = " + a );
            var b = a.toString();
            alert( "B = " + b );
        </script>
    </head>
    <body>
    </body>
</html>
EOD;

?>

由于 JavaScript 与 toString() 函数相关的工作方式,所有这些以前导致问题的问题都可以被消除。 现在所有字符串和数字都可以轻松转换。 此外,诸如对象之类的东西会导致 JavaScript 本身产生错误。 我相信这已经是最好的了。 剩下的唯一改进是 W3C 在 JavaScript 中仅包含 toHex() 和 fromHex() 函数。

更新:阅读下面的评论后,第一个 IF 语句应该在测试之后,以查看“s”是否是字符串。

The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:

function numHex(s)
{
    var a = s.toString(16);
    if ((a.length % 2) > 0) {
        a = "0" + a;
    }
    return a;
}

and

function strHex(s)
{
    var a = "";
    for (var i=0; i<s.length; i++) {
        a = a + numHex(s.charCodeAt(i));
    }

    return a;
}

I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:

function toHex(s)
{
    var re = new RegExp(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/);

    if (re.test(s)) {
        return '#' + strHex( s.toString());
    }
    else {
        return 'A' + strHex(s);
    }
}

Note that the numeric regular expression came from 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency.

Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that. HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work.

Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put "3.14159265" AS A NUMBER into a variable - all you will be able to get is the "3", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the hexadecimal value of 0xF causes the floating point value to be translated into an integer before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the floating point value against the 0xF value.

So the best thing to do, in this case, is to convert the 3.14159265 into a string and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.

So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a "#" to the front of numbers and "A" to the front of a character string coming back. See the toHex() function.

Have fun!

After another year and a lot of thinking, I decided that the "toHex" function (and I also have a "fromHex" function) really needed to be revamped. The whole question was "How can I do this more efficiently?" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.

So then the question became, "How do you know you are working with a hexadecimal string?". The answer is simple. Use the standard pre-string information that is already recognized around the world.

In other words - use "0x". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:

/////////////////////////////////////////////////////////////////////////////
//  toHex().  Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
    var l = "0123456789ABCDEF";
    var o = "";

    if (typeof s != "string") {
        s = s.toString();
    }

    if (s.substr(0,2).toLowerCase() == "0x") {
        return s;
    }

    for (var i=0; i<s.length; i++) {
        var c = s.charCodeAt(i);

        o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
    }

    return "0x" + o;
}

This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:

/////////////////////////////////////////////////////////////////////////////
//  fromHex().  Convert a hex string to ASCII text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
    var start = 0;
    var o = "";

    if (typeof s != "string") {
        s = s.toString();
    }

    if (s.substr(0,2).toLowerCase() == "0x") {
        start = 2;
    }

    for (var i=start; i<s.length; i+=2) {
        var c = s.substr(i, 2);

        o = o + String.fromCharCode(parseInt(c, 16));
    }

    return o;
}

Like the toHex() function, the fromHex() function first looks for the "0x" and then it translates the incoming information into a string if it isn't already a string. I don't know how it wouldn't be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has "0x" on the front of it.)

A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.

<?php

    echo <<<EOD
<html>
    <head><title>Test</title>
        <script>
            var a = -3.14159265;
            alert( "A = " + a );
            var b = a.toString();
            alert( "B = " + b );
        </script>
    </head>
    <body>
    </body>
</html>
EOD;

?>

Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.

Update : After reading the comments below, the first IF statement should come after the test to see if "s" is a string.

蓝眼泪 2024-07-12 19:46:44

带填充:

function dec2hex(i) {
   return (i+0x10000).toString(16).substr(-4).toUpperCase();
}

With padding:

function dec2hex(i) {
   return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
じее 2024-07-12 19:46:44

如果您想将数字转换为 RGBA 颜色值的十六进制表示形式,我发现这是这里的几个技巧的最有用组合:

function toHexString(n) {
    if(n < 0) {
        n = 0xFFFFFFFF + n + 1;
    }
    return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}

If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:

function toHexString(n) {
    if(n < 0) {
        n = 0xFFFFFFFF + n + 1;
    }
    return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}
天冷不及心凉 2024-07-12 19:46:44
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
}
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
}
泛滥成性 2024-07-12 19:46:44

没有循环:

function decimalToHex(d) {
  var hex = Number(d).toString(16);
  hex = "000000".substr(0, 6 - hex.length) + hex;
  return hex;
}

// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN

另外,不使用必须评估的循环测试不是更好吗?

例如,而不是:

for (var i = 0; i < hex.length; i++){}

for (var i = 0, var j = hex.length; i < j; i++){}

Without the loop:

function decimalToHex(d) {
  var hex = Number(d).toString(16);
  hex = "000000".substr(0, 6 - hex.length) + hex;
  return hex;
}

// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN

Also isn't it better not to use loop tests that have to be evaluated?

For example, instead of:

for (var i = 0; i < hex.length; i++){}

have

for (var i = 0, var j = hex.length; i < j; i++){}
雄赳赳气昂昂 2024-07-12 19:46:44

结合 RGB 值到十六进制函数的一些好主意(在 HTML/CSS 的其他位置添加 #):

function rgb2hex(r,g,b) {
    if (g !== undefined)
        return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
    else
        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}

Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the # elsewhere for HTML/CSS):

function rgb2hex(r,g,b) {
    if (g !== undefined)
        return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
    else
        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}
伏妖词 2024-07-12 19:46:44

对于任何感兴趣的人,这里有一个 JSFiddle 比较了这个问题的大多数答案

这是我最终采用的方法:

function decToHex(dec) {
  return (dec + Math.pow(16, 6)).toString(16).substr(-6)
}

另外,请记住,如果您希望将十进制转换为十六进制以在 CSS 中用作 颜色数据类型,您可能更喜欢从小数中提取 RGB 值并使用 rgb()

例如(JSFiddle):

let c = 4210330 // your color in decimal format
let rgb = [(c & 0xff0000) >> 16,  (c & 0x00ff00) >> 8,  (c & 0x0000ff)]

// Vanilla JS:
document.getElementById('some-element').style.color = 'rgb(' + rgb + ')'
// jQuery:
$('#some-element').css('color', 'rgb(' + rgb + ')')

这设置了#some-element的CSS <将 code>color 属性更改为 rgb(64, 62, 154)

For anyone interested, here's a JSFiddle comparing most of the answers given to this question.

And here's the method I ended up going with:

function decToHex(dec) {
  return (dec + Math.pow(16, 6)).toString(16).substr(-6)
}

Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().

For example (JSFiddle):

let c = 4210330 // your color in decimal format
let rgb = [(c & 0xff0000) >> 16,  (c & 0x00ff00) >> 8,  (c & 0x0000ff)]

// Vanilla JS:
document.getElementById('some-element').style.color = 'rgb(' + rgb + ')'
// jQuery:
$('#some-element').css('color', 'rgb(' + rgb + ')')

This sets #some-element's CSS color property to rgb(64, 62, 154).

陌路黄昏 2024-07-12 19:46:44

限制/填充到一定数量的字符:

function decimalToHex(decimal, chars) {
    return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}

Constrained/padded to a set number of characters:

function decimalToHex(decimal, chars) {
    return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}
恋竹姑娘 2024-07-12 19:46:44
var number = 3200;
var hexString = number.toString(16);

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

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

The 16 is the radix and there are 16 values in a hexadecimal number :-)

画骨成沙 2024-07-12 19:46:44

将十六进制颜色数字转换为十六进制颜色字符串:

使用 toString 和 ES6 padStart 的简单解决方案,用于将十六进制颜色数字转换为十六进制颜色字符串。

const string = `#${color.toString(16).padStart(6, '0')}`;

例如:

0x000000 将变为 #000000
0xFFFFFF 将变为 #FFFFFF

在此处的小提琴中查看此示例

Converting hex color numbers to hex color strings:

A simple solution with toString and ES6 padStart for converting hex color numbers to hex color strings.

const string = `#${color.toString(16).padStart(6, '0')}`;

For example:

0x000000 will become #000000
0xFFFFFF will become #FFFFFF

Check this example in a fiddle here

迷你仙 2024-07-12 19:46:44

如果数字是负数呢?

这是我的版本。

function hexdec (hex_string) {
    hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
    hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
    return parseInt(hex_string, 10);
}

And if the number is negative?

Here is my version.

function hexdec (hex_string) {
    hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
    hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
    return parseInt(hex_string, 10);
}
自由范儿 2024-07-12 19:46:43

如果您需要处理位字段或 32 位颜色等内容,那么您需要处理带符号的数字。 JavaScript 函数 toString(16) 将返回一个负的十六进制数,这通常不是您想要的。 这个函数做了一些疯狂的加法,使其成为一个正数。

function decimalToHexString(number)
{
  if (number < 0)
  {
    number = 0xFFFFFFFF + number + 1;
  }

  return number.toString(16).toUpperCase();
}

console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));

If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.

function decimalToHexString(number)
{
  if (number < 0)
  {
    number = 0xFFFFFFFF + number + 1;
  }

  return number.toString(16).toUpperCase();
}

console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));

三五鸿雁 2024-07-12 19:46:43

使用以下命令将数字转换为十六进制字符串:

hexString = yourNumber.toString(16);

并使用以下命令反转该过程:

yourNumber = parseInt(hexString, 16);

Convert a number to a hexadecimal string with:

hexString = yourNumber.toString(16);

And reverse the process with:

yourNumber = parseInt(hexString, 16);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文