Return to Snippet

Revision: 20277
at November 11, 2009 09:25 by aadsm


Updated Code
function toHex(number, min)
{
    var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
    var hex = '';
    var min = min || 2;
    var nibble;
    
    do
    {
        nibble = number & 0x0f;
        number = number >> 4;
        hex = hexes[nibble] + hex;
    }
    while( number );
    
    if( hex.length < min )
    {
        hex = new Array(min-hex.length+1).join('0') + hex;
    }
    
    return '0x'+hex;
}

Revision: 20276
at November 11, 2009 08:05 by aadsm


Initial Code
function toHex(number, min)
    {
        var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
        var hex = '0x';
        var min = min || 0;
        var nibble;
        
        do
        {
            nibble = number & 0x0f;
            number = number >> 4;
            hex += hexes[nibble];            
        }
        while( number );
        
        if( hex.length < min+2 )
        {
            hex = hex.slice(0,2) + new Array(min+3-hex.length).join('0') + hex.slice(2);
        }
        
        return hex;
    }

Initial URL

                                

Initial Description

                                

Initial Title
Convert a Number to an hexadecimal String

Initial Tags
number, convert

Initial Language
JavaScript