Author Topic: Number Base convertor  (Read 1191 times)

Offline fuzzy70

  • Community Developer
  • Prof. Inline
  • ******
  • Posts: 828
  • Look left, Look right, LOOK OUT!!
    • View Profile
Number Base convertor
« 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",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$, 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
« Last Edit: 2013-May-02 by Moru »
"Why don't you just make ten louder and make ten be the top number and make that a little louder?"
- "These go to eleven."

This Is Spinal Tap (1984)

Offline CW

  • Mr. Polyvector
  • ***
  • Posts: 155
    • View Profile
Re: Number Base convertor
« Reply #1 on: 2013-May-02 »
Very nice. This would be handy to have in the Math section.
-CW

Offline fuzzy70

  • Community Developer
  • Prof. Inline
  • ******
  • Posts: 828
  • Look left, Look right, LOOK OUT!!
    • View Profile
Re: Number Base convertor
« Reply #2 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
"Why don't you just make ten louder and make ten be the top number and make that a little louder?"
- "These go to eleven."

This Is Spinal Tap (1984)