Decimal to any base
Author |
Message |
wesyde
|
Posted: Mon May 31, 2010 7:19 pm Post subject: Decimal to any base |
|
|
I created this that it would covert any base number to a decimal.
I do not know how to do the opposite. From any decimal number to a selected base number, in this case base 5.
May someone be kind enough to teach me. Thank you:)
function hextodec (ihex : string) : int
var sFirst : string := ihex (1)
var sSecond : string := ihex (2)
var sThird : string := ihex (3)
var sFour : string := ihex (4)
result (strint (sFirst) * 125) + (strint (sSecond) * 25) + (strint (sThird) * 5) + strint (sFour)
end hextodec
var sHextodec : string := ""
get sHextodec
put hextodec (sHextodec) |
|
|
|
|
|
Sponsor Sponsor
|
|
|
DtY
|
Posted: Mon May 31, 2010 8:13 pm Post subject: RE:Decimal to any base |
|
|
First of all, when you convert, you will take out each digit separately, so you will end up with a single digit, which needs to be mapped onto the corresponding character, this can be done with a big if or select statement, but I prefer to create an array with all the digits as strings; ["0", "1"..."A","B"...], this should extend as far as you want to be able to convert to.
To do the conversion, you need to "pull" digits out until the number is zero, to do this, use modulo, and then divide,
[syntax="Turing"]% n is the number to convert
% base is the base to convert to
digit = n mod base;
n /= base[/code]
Imagine the example of base ten (which doesn't do anything practical, but can help to understand the problem), say you want to convert the number 123, first, mod 10 will tell you the right most digit (123 mod 10 = 3), then you need to shift the number, so that the next digit is at the right (123 / 10 = 12). You then want to check what digit this is by looking it up in the table (this table wont really be useful unless converting to a base higher than 10).
NB;; if you'd not noticed yet, this will process the number "backwards", you will get the least significant digit first, the easiest way to handle this is to put it all into a string, and then reverse the string.
As a more practical example, here is converting 123 to base 16 (hexadecimal); (pseudocode)
code: | var n = 123;
var base = 16;
var digits = "";
var digMap = "0123456789ABCDEF";
var digit;
digit = n mod base;
digits += digMap[digit];
n /= b;
% repeat until n = 0 |
If you haven't learned about modulo yet: https://secure.wikimedia.org/wikipedia/en/wiki/Modulo_operation |
|
|
|
|
|
wesyde
|
Posted: Mon May 31, 2010 8:19 pm Post subject: Re: Decimal to any base |
|
|
thank you. I understand it alot more now. But may you please explain this part more in regular coding language.
digit = n mod base;
digits += digMap[digit];
n /= b; |
|
|
|
|
|
|
|