How to convert decimal to hexadecimal in JavaScript

后端 未结 27 2574
臣服心动
臣服心动 2020-11-21 23:05

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

相关标签:
27条回答
  • 2020-11-21 23:35

    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
    
    0 讨论(0)
  • 2020-11-21 23:36

    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++){}
    
    0 讨论(0)
  • 2020-11-21 23:36

    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;
    }
    
    0 讨论(0)
  • 2020-11-21 23:38

    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.

    0 讨论(0)
  • 2020-11-21 23:39

    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.

    0 讨论(0)
  • 2020-11-21 23:39

    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

    0 讨论(0)
提交回复
热议问题