# GLBasic forum

## Codesnippets => Math => Topic started by: fuzzy70 on 2013-Apr-27

Title: Number Base convertor
Post by: fuzzy70 on 2013-Apr-27
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
Code: (glbasic) [Select]
`SETCURRENTDIR("Media")LOADFONT "smalfont.png",0SETFONT 0LOCAL 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,1NEXTSHOWSCREENKEYWAITENDFUNCTION 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\$, loop-1, 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`
Title: Re: Number Base convertor
Post by: CW on 2013-May-02
Very nice. This would be handy to have in the Math section.
-CW
Title: Re: Number Base convertor
Post by: fuzzy70 on 2013-May-02
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