eSnippets.net, a code gallery for creating, saving and sharing all kinds of code snippets.

Decimal to hexadecimal converter — Javascript

Posted On: Friday, April 3, 2015 at 1:44 AM

Convert decimal numbers to hexadecimal with this simple javascript function.

function integerDecimalToBinary(decValue) {
var binaryValue = '', integerResult = decValue;

do {
binaryValue = integerResult % 2 + binaryValue;
integerResult = Math.floor(integerResult / 2);
} while(integerResult != 0)

return binaryValue;
}

var binToHexTable = {
'0000': 0,
'0001': 1,
'0010': 2,
'0011': 3,
'0100': 4,
'0101': 5,
'0110': 6,
'0111': 7,
'1000': 8,
'1001': 9,
'1010': 'A',
'1011': 'B',
'1100': 'C',
'1101': 'D',
'1110': 'E',
'1111': 'F'
};

function decToHex(decValue) {
var binValue = integerDecimalToBinary(decValue),
groupsOfFour = [];

for(var charIndex = binValue.length - 1, charsOutOfFour = 0, fourChars = ''; charIndex >= 0; charIndex--) {
fourChars = binValue.charAt(charIndex) + fourChars;

if(charsOutOfFour == 3) {
groupsOfFour.push(fourChars);
charsOutOfFour = 0;
fourChars = '';
}
else {
charsOutOfFour++;
}
}

if(fourChars != '' && fourChars.length < 4) {
var numberOfEmptyChars = 4 - fourChars.length;
for(var charIndex = 0; charIndex < numberOfEmptyChars; charIndex++) {
fourChars = '0' + fourChars;
}
groupsOfFour.push(fourChars);
}

var hexValue = '';
for(var groupIndex = 0; groupIndex < groupsOfFour.length; groupIndex++) {
hexValue = binToHexTable[groupsOfFour[groupIndex]] + hexValue;
}

return hexValue;
}

You need to be logged in to comment! x

rpjs

Joined on Saturday, May 3, 2014
Contributed 29 Snippets

Get Social and Share

Tags