|
Post by Eric on Aug 27, 2005 3:27:46 GMT
I know that you can use parseint to change them, but I wanted to do it all by hand. Tell me what you think, and feel free to use it. var hex = '0123456789ABCDEF'; function d2h(num) { if(num.toString().match(/\d/i)) { var newHex = ''; for(var getExp = 1; Math.pow(16,getExp)-1 < num; getExp++) { } getExp--; while(getExp >= 0) { for(var checkOk = 15; checkOk >= 0; checkOk--) { if(checkOk * Math.pow(16,getExp) <= num) { newHex += hex.charAt(checkOk); num -= (checkOk * Math.pow(16,getExp)); getExp--; checkOk = -1; } } } if(newHex.length < 1) newHex = '0'; return newHex; }else{ alert("The number can only contain digits."); return 0; } } function h2d(hexnum) { hexnum = hexnum.toString(); if(hexnum.match(/[0-9A-Z]/i)) { hexnum = hexnum.toUpperCase(); var end = 0; for(var x = 0; x < hexnum.length; x++) { end += hex.indexOf(hexnum.charAt(x)) * Math.pow(16, hexnum.length - 1 - x); } return end; }else{ alert("The hexadecimal number can only contain numbers 0 through 9 and letters A through F"); return 0; } }
|
|
Peter
New Member
God
Posts: 6
|
Post by Peter on Aug 27, 2005 12:26:55 GMT
Nice job Eric, works well. Maybe take it a step further then parseInt(). With parseInt, you can only use 2 characters to get the decimal. ie.. parseInt("FF", 16); Take yours a step further so that if a user was to do... h2d("FFFFFF"); ...it would return 255255255, and maybe the other way as well. Anyway, like I said, good job
|
|
|
Post by Eric on Aug 27, 2005 13:15:29 GMT
Huh? You got me confused there. I didn't use parseint if that's what you mean. I built it all from scratch. It should be able to handle FFFFFF. Edit: Ah I see what you're saying. I'm doing this by true hex, I think what you are saying is the RGB hex, right?
|
|
Peter
New Member
God
Posts: 6
|
Post by Peter on Aug 27, 2005 14:55:36 GMT
Yeah, I think it would be more useful if it could allow for RBG hex, so FFFFFF could be inputted.
|
|