hextodec and dectohex in Javascript


Today, I was so excited by this ‘hexadecimal-to-decimal-conversion’ explanation (http://www.youtube.com/watch?v=lTjFFEtmZyA) that I’ve refreshed my mind by writing this javascript implementation:

function hextodec(hex) {
    var final = 0;
    var letters = { A : 10, B : 11, C : 12, D : 13, E : 14, F : 15 };
    var len = hex.length;
    for(var i=0;i<len;i++) {
        var ch = hex.charAt(len-i-1);
        if( ch in letters )
            ch = letters[ch];
        var shiftBy = 4*i;
        var sub = ch << shiftBy;
        final += sub;
    }
    return final;
}

console.log( hextodec('4C3') );    //yields 1219

… and backwards …

function dectohex(dec) {
    if( dec < 10 ) return dec;
    var final = '';
    var letters = { 10 : 'A', 11 : 'B', 12 : 'C', 13 : 'D', 14 : 'E', 15 : 'F' };
    var digit = dec;
    while(digit > 0) {
        var rest = 0;

        if( digit < 16 )
            rest = digit;
        else
            rest = digit%16;

        var letter = ( rest>9 ) ? letters[rest] : rest;
        final = letter + '' + final;
        digit = (digit-rest)/16;
    }
    return final;
}

console.log( dectohex(1219) );     //yields '4C3'
Advertisements

One thought on “hextodec and dectohex in Javascript

  1. This unique article, Sliding Panel Tracks “hextodec and
    dectohex in Javascript | softwarechaos” ended up being beneficial.
    I’m impressing out a duplicate to demonstrate to my close friends.
    Regards-Kate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s