How to convert decimal to hexadecimal in JavaScript

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

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

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

    With padding:

    function dec2hex(i) {
       return (i+0x10000).toString(16).substr(-4).toUpperCase();
    }
    
    0 讨论(0)
  • 2020-11-21 23:41
    function toHex(d) {
        return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
    }
    
    0 讨论(0)
  • 2020-11-21 23:41

    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).

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

    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)
    {
        if (s.substr(0,2).toLowerCase() == "0x") {
            return s;
        }
    
        var l = "0123456789ABCDEF";
        var o = "";
    
        if (typeof s != "string") {
            s = s.toString();
        }
        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 (s.substr(0,2).toLowerCase() == "0x") {
            start = 2;
        }
    
        if (typeof s != "string") {
            s = s.toString();
        }
        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.

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

    You can do something like this in ECMAScript 6:

    const toHex = num => (num).toString(16).toUpperCase();
    
    0 讨论(0)
  • 2020-11-21 23:45
    var number = 3200;
    var hexString = number.toString(16);
    

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

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