Convert Hex string to binary

Share your advanced PureBasic knowledge/code with the community.
User avatar
Michael Vogel
Addict
Addict
Posts: 2663
Joined: Thu Feb 09, 2006 11:27 pm
Contact:

Convert Hex string to binary

Post 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)
User avatar
idle
Always Here
Always Here
Posts: 5019
Joined: Fri Sep 21, 2007 5:52 am
Location: New Zealand

Re: Convert Hex string to binary

Post by idle »

Thanks

Code: Select all

s.s= Hex(4276996862) 
Debug CreateHexFile(@s)
Debug s 
infratec
Always Here
Always Here
Posts: 6810
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Convert Hex string to binary

Post 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.
Post Reply