Page 1 of 1

Convert Hex string to binary

Posted: Wed Oct 13, 2021 7:10 pm
by Michael Vogel
Needed to convert different hex strings ("$AA,BB,..." or "AABB..." or "$AA, $BB,...", etc.) to a binary file.

Here's the resulting code:

Code: Select all

Global temp.s=GetTemporaryDirectory()+"Hex Data.bin"
Debug temp

Macro CreateHexByte(value)
	
	WriteByte(0,(value))
	Debug "%"+Str((value))+" ($"+Hex((value))+")"
	a=0

EndMacro

Procedure CreateHexFile(*s.string)

	Protected a,b,c

	If CreateFile(0,temp,#PB_Ascii)

		Repeat

			c=PeekA(*s)
			If c : c|$20 : EndIf
			*s+SizeOf(Character)

			Select c
			Case '0' To '9'
				If a
					CreateHexByte(b<<4+c-'0')
				Else
					a=#True
					b=c-'0'
				EndIf
			Case 'a' To 'f'
				If a
					CreateHexByte(b<<4+c-'W')
				Else
					a=#True
					b=c-'W'
				EndIf
			Case ' ',',','$',#CR,#LF,#Null
				If a
					CreateHexByte(b)
				EndIf
			Default
				Debug "ERROR '"+Chr(c)+"'"
				c=#Null
				*s=#Null
			EndSelect

		Until c=#Null
		
		CloseFile(0)
		
	Else
		*s=#Null
	EndIf

	ProcedureReturn Bool(*s)

EndProcedure

s.s=GetClipboardText()
Debug CreateHexFile(@s)

Re: Convert Hex string to binary

Posted: Wed Oct 13, 2021 10:17 pm
by idle
Thanks

Code: Select all

s.s= Hex(4276996862) 
Debug CreateHexFile(@s)
Debug s 

Re: Convert Hex string to binary

Posted: Wed Oct 13, 2021 10:22 pm
by infratec
Don't use fixed 0 for CreateFile(). Use #PB_Any.
Else someone can end in trouble if he uses also 0 as file.

If you use *s.Character as parameter, you can avoid to call PeekA() as procedure.
Then you can use *s\c instead.