Page 1 of 1

convert binary octal hex to decimal

Posted: Thu Dec 26, 2019 6:27 am
by idle
convert binary octal hex to decimal with constant values or strings, with an Oct equivalent of Bin,Hex

Code: Select all

Procedure.s Oct(number.q) 
  Protected s.s=Space(8*SizeOf(Character)) 
  For a = 7 To 0 Step -1
    PokeS(@s+a*SizeOf(Character),Str(number & 7),SizeOf(Character),#PB_String_NoZero) 
    number >> 3 
  Next   
  ProcedureReturn Trim(s,"0") 
EndProcedure   

;converts and assigns a variable with a constant in the given base 2,8,16
Macro _DEC(var,val,base) 
  EnableASM 
  CompilerSelect base 
    CompilerCase 2 
      mov var, val#b 
    CompilerCase 8
      mov var, val#o 
    CompilerCase 16
      mov var, 0#val#h    
  CompilerEndSelect 
  DisableASM    
EndMacro 

;take a string from respective bases 16,8,2 convert to decimal  

Procedure.q ConvertToDecimal(*n.Character, base)
  Protected d.u, r.q
  Repeat
    d = *n\c - 48
    If d > 9
      d | 32 : If d > 48 : d - 39 : EndIf
    EndIf
    If d >= base : Break : EndIf
    r = (r * base) + d
    *n + SizeOf(Character)
  ForEver
  ProcedureReturn r
EndProcedure


Define a.i

 _DEC(a,10101,2)   
 Debug "Dec " + Str(a) + " Bin " + Bin(a) 
 _DEC(a,644,8)
 Debug "Dec " + Str(a) + " Oct " + Oct(a) 
 _DEC(a,ABC123,16)
 Debug "Dec " + Str(a) + " Hex " + Hex(a) 

Debug ConvertToDecimal(@"ABC123",16) 
Debug ConvertToDecimal(@"644",8)
Debug ConvertToDecimal(@"10101",2) 



Re: convert binary octal hex to decimal

Posted: Thu Dec 26, 2019 11:12 am
by Mesa
I've got an error on Windows XP32b+PB5.71 LTS x86
PureBasic.asm[111]:MOV qword[v_a],1010b
error:illegal instruction.
M.

Re: convert binary octal hex to decimal

Posted: Thu Dec 26, 2019 12:06 pm
by wilbert
Mesa wrote:I've got an error on Windows XP32b+PB5.71 LTS x86
If you define a as .i instead of .q it should work.

Here's also a to decimal conversion without the need of Pow.

Code: Select all

Procedure.q ConvertToDecimal(*n.Character, base) 
  Protected d.u, r.q
  Repeat
    d = *n\c - 48
    If d > 9
      d | 32 : If d > 48 : d - 39 : EndIf
    EndIf
    If d >= base : Break : EndIf
    r = (r * base) + d
    *n + SizeOf(Character)
  ForEver
  ProcedureReturn r 
EndProcedure 

Debug ConvertToDecimal(@"abc123", 16) 
Debug ConvertToDecimal(@"644", 8)
Debug ConvertToDecimal(@"10101", 2) 

Re: convert binary octal hex to decimal

Posted: Thu Dec 26, 2019 8:02 pm
by idle
Thanks Wilbert that's a much better solution, edited post

Re: convert binary octal hex to decimal

Posted: Fri Dec 27, 2019 1:04 pm
by Kwai chang caine
The code for convertion are always interesting 8) (even if in don't understand all) :oops:
This two codes works, thanks for sharing 8)