I am keen to know the source code for .toString(16) in javascript Because I would like to check logic of how the dec code converted to hex code?
-
3That just converts it to hex. There are lot of sample code available to convert from dec to hex.Praveen Kumar Purushothaman– Praveen Kumar Purushothaman2016-02-12 10:11:03 +00:00Commented Feb 12, 2016 at 10:11
-
Also see stackoverflow.com/questions/923771/…PM 2Ring– PM 2Ring2016-02-12 11:06:43 +00:00Commented Feb 12, 2016 at 11:06
Add a comment
|
1 Answer
Base := 16
HexNumber := ""
while(DecNumber > 0) {
HexNumber := Concat(DecNumber % Base, HexNumber)
DecNumber := Floor(DecNumber / Base)
}
Works for any base. In hex, obviously you'll have to convert 10+ to A-F.
Edit: Here is a version in javascript:
function toBaseString(base, decNumber) {
var hexNumber = '';
while(decNumber > 0) {
var hexDigit = decNumber % base;
if(hexDigit >= 10) {
hexDigit = String.fromCharCode(hexDigit + 87);
}
hexNumber = hexDigit + hexNumber;
decNumber = Math.floor(decNumber / base);
}
return hexNumber;
}
6 Comments
Praveen Kumar Purushothaman
Possible to change it to JavaScript? This is not JavaScript right?
Neil
@PraveenKumar Here is a version in javascript. There is an added portion to convert 10+ numbers to a-f in case of hex strings. Works equally well with base 2.
Praveen Kumar Purushothaman
Looks awesome buddy.
Mr.arrogant
Hi neil please explain this line --> hexDigit = String.fromCharCode(hexDigit + 87);
Neil
In ASCII, 97 corresponds to 'a'. Calling String.fromCharCode converts a number to its equivalent ascii character and so by taking hexDigit which is at least 10 and adding 87, I'm mapping it 1 to 1 to an ascii character. So 10 becomes 'a', 11, becomes 'b', etc. If I were using base 20, then I would start having characters like 'j'. That said, numbers may not look so hot in base 9842.
|