Page 1 of 1

convert HEX value to ASCII

Posted: Sun May 17, 2009 10:32 pm
by nicolaus
Hello,

how i can convert a HEX value in 2 byte steps to ASCII ?

eg:
HEX = $696D6C5666374861645137307A6C466C516E6F2F73736937614A616C734E4C765830636751345930544E543232345A6775396C6C43683957374361656D58726333464D79484C704672413D3D0D0A

Thanks,
Nico

Posted: Sun May 17, 2009 10:52 pm
by DoubleDutch
The hex string you listed doesn't make much sense - but this should work...

Code: Select all

Procedure.s HexStr2Ascii(string$)
	For loop=1 To Len(string$) Step 2
		result$+Chr(Val("$"+Mid(string$,loop,2)))
	Next
	ProcedureReturn result$
EndProcedure

HEX$="696D6C5666374861645137307A6C466C516E6F2F73736937614A616C734E4C765830636751345930544E543232345A6775396C6C43683957374361656D58726333464D79484C704672413D3D0D0A"

Debug(HexStr2Ascii(HEX$))

Posted: Fri May 22, 2009 8:36 pm
by Hroudtwolf
Hi,

Maybe this could be a little bit faster.

Code: Select all

; Hex string to char string
; 2009 By Hroudtwolf
; PureBasic 4.x
; Windows, Linux, OS X

Structure tHexPair
   StructureUnion
      s.s { 2 }
      c.c [ 2 ]
   EndStructureUnion
EndStructure

Procedure.i HexPair2Dec ( *ptrStr.CHARACTER )
   Protected nValue  .i
   Protected nI      .i
   
   If Not *ptrStr
      ProcedureReturn 0
   EndIf

   For nI = 0 To 1
      Select *ptrStr\c
         Case 'a' To 'f'
         nValue = ( nValue << 4 ) + ( *ptrStr\c - 87 )
         
         Case 'A' To 'F'
         nValue = ( nValue << 4 ) + ( *ptrStr\c - 55 )
         
         Case '0' To '9'
         nValue = ( nValue << 4 ) + ( *ptrStr\c - 48 )
         
         Default
         nValue = ( nValue << 4 ) + ( *ptrStr\c - 55 )
         
      EndSelect   
      *ptrStr + SizeOf ( CHARACTER )
   Next nI
   
   ProcedureReturn nValue
EndProcedure

Procedure.s HexStr2Ascii ( *ptrStr.tHexPair )
   Protected sOutput .s
  
   If Not *ptrStr
      ProcedureReturn ""
   EndIf   
   
   While *ptrStr\c [ 1 ]
      sOutput + Chr ( HexPair2Dec ( @ *ptrStr\s ) )
      *ptrStr + SizeOf ( tHexPair )
   Wend
   
   ProcedureReturn sOutput
EndProcedure

Define.s sHex = "696D6C5666374861645137307A6C466C516E6F2F73736937614A616C734E4C765830636751345930544E543232345A6775396C6C43683957374361656D58726333464D79484C704672413D3D0D0A"

Debug HexStr2Ascii ( @ sHex )  
Best regards

Wolf