-2

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?

2

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Possible to change it to JavaScript? This is not JavaScript right?
@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.
Looks awesome buddy.
Hi neil please explain this line --> hexDigit = String.fromCharCode(hexDigit + 87);
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.