Click to See Complete Forum and Search --> : [RESOLVED] convert a decimal number to hexadecimal


hitai
October 3rd, 2006, 12:03 AM
I`ve been serching for a built-in javascript function that converts a decimal number to hexadecimal but can`t find any. Does such a function actually exist, or do i hav to write my own code to perform this task?

mmetzger
October 3rd, 2006, 10:22 AM
Yeah - there's a ton...

http://www.google.com/search?q=javascript+decimal+to+hex

PeejAvery
October 3rd, 2006, 10:34 AM
There is no JavaScript function that will do it, but you can. I don't know if you are a beginner or not so forgive me if you are able to create one yourself. Below is some code.

function tohex(value){
// Array of hex characters
var hexchars = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F');
// Repeat failsafe
var times = 0;
// Make sure it is an integer
var integer = parseInt(value,10);
retval = '';
if (isNaN(integer)){retval = 'NaN';}
else{
while (integer > 0.9){
times++;
// Create test copy
testinteger = integer;
// Do conversion
retval = hexchars[testinteger % 16] + retval;
integer = Math.floor(testinteger / 16);
if (times > 100){
retval = 'NaN';
break;
}
}
}
return retval;
}

mmetzger
October 3rd, 2006, 03:13 PM
D'oh... sorry - missed the "built-in" part of that request...

hitai
October 3rd, 2006, 11:01 PM
Ah...thanks for the replies. Sad that they didn`t include a built-in function for such a common task in programming

PeejAvery
October 4th, 2006, 08:40 AM
Ah...thanks for the replies. Sad that they didn`t include a built-in function for such a common task in programming
You must remember that JavaScript was created with the purpose of making web pages more interactive. Since Hex and the average person don't go together, I can see why it is not a JavaScript thing.