HexToVal convert hex to value
Posted: Fri Jan 19, 2024 10:17 am
convert hex strings to value , should work for any length.
ignores non hex chars so you could have a string like "$10 $20" or "0x1020"
ignores non hex chars so you could have a string like "$10 $20" or "0x1020"
Code: Select all
Structure m128
StructureUnion
a.a[16]
u.u[8]
l.l[4]
q.q[2]
EndStructureUnion
EndStructure
Structure m256
StructureUnion
a.a[32]
u.u[16]
l.l[8]
q.q[4]
EndStructureUnion
EndStructure
Procedure HexToVal(hex.s)
If hex <> ""
Protected *p.Unicode
Protected len = Len(hex)
Protected *out = AllocateMemory(len)
Protected *buff.Ascii = *out
Protected *hex=@hex + (StringByteLength(hex)-2)
Protected ct,v
Static Dim lut(102)
If lut(48) <> 1
lut(48)=1
lut(49)=2
lut(50)=3
lut(51)=4
lut(52)=5
lut(53)=6
lut(54)=7
lut(55)=8
lut(56)=9
lut(57)=10
lut(65)=11
lut(66)=12
lut(67)=13
lut(68)=14
lut(69)=15
lut(70)=16
lut(97)=11
lut(98)=12
lut(99)=13
lut(100)=14
lut(101)=15
lut(102)=16
EndIf
*p=*hex
While *p\u <> 0
If *p\u <= 102
If lut(*p\u) <> 0
v = lut (*p\u)-1
If (ct & 1)
*buff\a | v << 4
*buff + 1
Else
*buff\a | v
EndIf
ct+1
EndIf
EndIf
*p-2
Wend
ProcedureReturn ReAllocateMemory(*out,ct)
EndIf
EndProcedure
Procedure.s ValToHex(*mem)
Structure mA
a.a[0]
EndStructure
Protected *ma.ma, out.s
*ma=*mem
sz = ((MemorySize(*mem)-1) >> 1)
If sz >= 0
For a = sz To 0 Step -1
out + Hex(*ma\a[a])
Next
EndIf
ProcedureReturn out
EndProcedure
CompilerIf #PB_Compiler_IsMainFile
Global m128.s ="$12B0D868D117D7C8379DE50FA97A7b x ;GA0;" ;ignores non hex chars
Global *m128.m128 = HexToVal(m128)
Global m256.s = "12B0D868D117D7C8379DE50FA97A7BA012B0D868D117D7C8379DE50FA97A7BAB"
Global *m256.m256 = HexToVal(m256)
Debug ValToHex(*m128)
Debug ValToHex(*m256)
FreeMemory(*m128)
FreeMemory(*m256)
Debug ValToHex(HexToVal("$F"))
Debug ValToHex(HexToVal("DEF"))
Debug ValToHex(HexToVal("01234"))
Debug ValToHex(HexToVal("9abcde"))
Debug ValToHex(HexToVal("1FFFFFFFFFFFFFDC"))
CompilerEndIf