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?
Asked
Active
Viewed 1,188 times
-2

Praveen Kumar Purushothaman
- 164,888
- 24
- 203
- 252

Mr.arrogant
- 47
- 7
-
3That just converts it to hex. There are lot of sample code available to convert from dec to hex. – Praveen Kumar Purushothaman Feb 12 '16 at 10:11
-
Also see http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net – PM 2Ring Feb 12 '16 at 11:06
1 Answers
1
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;
}

Neil
- 5,762
- 24
- 36
-
1Possible to change it to JavaScript? This is not JavaScript right? – Praveen Kumar Purushothaman Feb 12 '16 at 10:43
-
@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. – Neil Feb 12 '16 at 10:56
-
-
Hi neil please explain this line --> hexDigit = String.fromCharCode(hexDigit + 87); – Mr.arrogant Feb 12 '16 at 11:38
-
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. – Neil Feb 12 '16 at 11:48
-