Created
January 12, 2023 21:55
-
-
Save cancel-cloud/e844158bad96f307a763c7a5c30dfc06 to your computer and use it in GitHub Desktop.
Zahlensystem Converter JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convert(input, sourceUnit, targetUnit) { | |
let result = ""; | |
let num = input; | |
let temp = ""; | |
while (num > 0) { | |
let remainder = num % sourceUnit; | |
temp = remainder.toString(sourceUnit) + temp; | |
num = Math.floor(num / sourceUnit); | |
} | |
let decimal = 0; | |
let power = 0; | |
for (let i = temp.length - 1; i >= 0; i--) { | |
let char = temp.charAt(i); | |
let digit = char.charCodeAt(0) <= 57 ? char - '0' : char.toUpperCase().charCodeAt(0) - 55; | |
decimal += digit * Math.pow(sourceUnit, power); | |
power++; | |
} | |
while (decimal > 0) { | |
let remainder = decimal % targetUnit; | |
result = (remainder > 9 ? String.fromCharCode(remainder + 55) : remainder) + result; | |
decimal = Math.floor(decimal / targetUnit); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment