Page 1 of 1

Hex2Bin

Posted: Fri Nov 07, 2008 5:09 pm
by pdwyer
More bugs found :oops:
One in memory usage and one in byte order: it's set up to pass longs and quads etc so the with the significant bits of those types means I'm backwards for the way I actually want to use this function (in large blocks of memory)

Will fix

====================================

I needed this so I thought I'd post it, give poeple a chance to catch my bugs for me :)

Should work with memory blocks up to a couple of gig.

Pass it a hex string and a pointer to a memory buffer (valid with atleast a len of 1) and it will resize as needed. This is an example with a quad but it could be anything or just an arbitrary block.

(Bug Fix - third parameter)
If you leave the last parameter as 0 then the buffer will be allocated exactly, this can be a problem though as in the example below using a quad the peekq() will grab 8 bytes, if you don't allocate 8 and put a small number in the hex then the function will read off the end and the garbage there will skew your results, this would be needed if you desire a type of certain size

Code: Select all


Structure Bytes 
    Byte.b[0] 
EndStructure 

Procedure Hex2Bin(Hex.s, *MemoryBuffer, BufferSize = 0)

    HexLen = Len(Hex)
    BufLen.l = HexLen / 2
    
    If hexlen % 2 = 1
        BufLen = BufLen + 1
    EndIf    

    If BufferSize > 0: BufLen = BufferSize:EndIf 
    *MemoryBuffer = ReAllocateMemory(*MemoryBuffer,BufLen)
    
    *WorkBuff.Bytes = *MemoryBuffer
    BufferPtr = 0
    
    For i = HexLen -1 To 1  Step -2 
        *WorkBuff\Byte[BufferPtr] = Val("$" + Mid(Hex,i,2))
        BufferPtr =  BufferPtr + 1
        
        If HexLen % 2 = 1
            *WorkBuff\Byte[BufferPtr] = Val("$" + Mid(Hex,1,1))
        EndIf
    
    Next

EndProcedure


*Buffer = AllocateMemory(1)
Number.l = 212
temp.s = Hex(Number)
Debug temp
Debug number

Hex2Bin(temp, *Buffer,4)

Debug PeekL(*Buffer)


Posted: Fri Nov 07, 2008 9:00 pm
by akj
If the procedure Hex2Bin() does what the name suggests, then I would have thought the code below (which works with quad-length values) would be a far better way to do it:

Code: Select all

h$ = "D4"
Debug Bin(Val("$"+h$))

Posted: Sat Nov 08, 2008 1:00 am
by pdwyer
True, but this is not really for those normal data types, it's just to create an example to check the output.

In the program I'm writing I have a search feature for binary files and you can enter an arbitrary length of hex data to search. In order to match I need to turn this into a pointer to a buffer of length n bytes (this can be any length) and so I wrote this

I will probably make a quick change to the above function so that it returns the lenght that it has allocated too.