Re: Question About Z-Level Number Thingie
Colin Taylor wrote:
>I don't know if Lucius' suggestion helped you, but here is a short function
>which converts a decimal integer to any base between 2 and 36...
>
>sequence char, out_str
>char = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>out_str = ""
>
>function convert_base(integer num, integer base)
> if num >= base then
> out_str = convert_base(floor(num/base), base)
> & char[remainder(num,base)+1]
> else
> out_str &= char[num+1]
> end if
> return out_str
>end function
Not bad! Being in something of a picky mood, though, I took it upon myself
to rewrite the above routine, and also to write its partner in crime. This
code is given below, along with a "sanity test" to insure that everything
converts back & forth properly.
Further suggestions/modifications/improvements are encouraged!
-- written by Gabriel Boehme
-- based on code by Colin Taylor
include misc.e
constant NUM_CHAR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
type base_type(integer x)
return x >= 2 and x <= length(NUM_CHAR)
end type
function int_to_base_n(integer int, base_type base)
sequence base_n
base_n = ""
while int >= base do
base_n = prepend(base_n, NUM_CHAR[remainder(int,base)+1])
int = floor(int/base)
end while
base_n = prepend(base_n, NUM_CHAR[int+1])
return base_n
end function
function base_n_to_int(sequence base_n, base_type base)
integer int
int = 0
base_n = reverse(base_n)
for pos = 1 to length(base_n) do
int += (find(base_n[pos], NUM_CHAR)-1) * power(base, pos-1)
end for
return int
end function
-- sanity test
sequence string
integer result
for base = 2 to 36 do
for number = 0 to 100 do
string = int_to_base_n(number, base)
printf(1, "%s\n", {string})
result = base_n_to_int(string, base)
if number != result then
printf(1, "%d != %d", {number, result})
abort(0)
end if
end for
end for
puts(1, "\nYay!\n")
Hep yadda,
Gabriel Boehme
----------
[...] we have a suffocating sense of luxury and no sense at all of liberty.
All the pleasure-hunters seem to be themselves hunted. All the children of
fortune seem to be chained to the wheel. There is very little that really
even pretends to be happiness in all this sort of harassed hedonism.
G.K. Chesterton
----------
|
Not Categorized, Please Help
|
|