GLBasic forum
Codesnippets => Math => Topic started by: fuzzy70 on 2013Apr27

Like it says in the title, A converter for different number bases ranging from base 2 to base 36.
Enjoy =D
Lee
p.s if you use this example I seriously recommend you create a font to view the results, unless eyestrain/headache are your thing :P
SETCURRENTDIR("Media")
LOADFONT "smalfont.png",0
SETFONT 0
LOCAL num$,loop%
FOR loop=1 TO 20
num$=Base_convert$("ff",16,loop)
PRINT "Base="+loop,0,loop*17,1
PRINT "Result="+num$,100,loop*17,1
NEXT
SHOWSCREEN
KEYWAIT
END
FUNCTION Base_convert$: number$,frombase%,tobase%
LOCAL charset$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOCAL loop%,value%,temp%,result$
number$=UCASE$(number$)
IF frombase < 2 OR frombase > 36 OR tobase% < 2 OR tobase% > 36 THEN RETURN number$
FOR loop = 1 TO LEN(number$)
value = INSTR(charset$, MID$(number$, loop1, 1))
IF value < 0 OR value >= frombase THEN RETURN
temp = temp + value * POW(frombase,(LEN(number$)  loop))
NEXT
IF temp < 0 THEN RETURN number$
result$ = ""
REPEAT
value = MOD(temp,tobase)
temp = FLOOR(temp / tobase)
result$ = MID$(charset$, value , 1) + result$
UNTIL temp <= 0
RETURN result$
ENDFUNCTION
// Uncomment for GLBasic V10
//FUNCTION Floor%: value%
// RETURN INTEGER(value)
//ENDFUNCTION

Very nice. This would be handy to have in the Math section.
CW

oopsie, I forgot there was a Math section :D
It's one of those type of snippets that could go into either really. A mod is more than welcome to move it if they think that would be a better place for it.
Lee