Sign in to follow this  
Followers 0
mrider

Bug in _HexToString ?

1 post in this topic

Consider the following code:

$a = _StringToHex("foo" );
MsgBox( 0, "DEBUG", "a: " & $a );
$b = Dec( $a );
MsgBox( 0, "DEBUG", "b: " & $b );
$c = Hex( $b );
MsgBox( 0, "DEBUG", "c: " & $c );
$d = _HexToString( $c );           <-- THIS FAILS
MsgBox( 0, "DEBUG", "d: " & $d );  <-- EMPTY WINDOW
MsgBox( 0, "ERROR", @error );     <-- NO ERROR DETECTED

; The following just proves that _HexToString will work without the leading zeros
$d = _HexToString( "666F6F" );
MsgBox( 0, "DEBUG", "d: " & $d );
MsgBox( 0, "ERROR", @error );

As you can see when running the code, it's possible to cause problems when translating otherwise valid input. I found this accidentally while trying to transport information across the network. I have made the following changes to my own String.au3 UDF. But I haven't had time to test the changes extensively, so there may be unknown ramifications to using this code. But here is my complete _HexToString UDF:

Func _HexToString($strHex)
    Local $strChar, $aryHex, $i, $iDec, $Char, $iOne, $iTwo, $started
    
    $aryHex = StringSplit($strHex, "")
    If Mod($aryHex[0], 2) <> 0 Then
        SetError(1)
        Return -1
    EndIf
    
    #cs
      This will stay False until the first non-zero character is found.
      The idea is to ignore leading zeros until first "real" character is
      found.  Typically "Chr(0)" means "end of string", so we don't want
      that at the beginning of our result.
    #ce
    $started = False
    
    For $i = 1 To $aryHex[0]
        $iOne = $aryHex[$i]
        $i = $i + 1
        $iTwo = $aryHex[$i]
        $iDec = Dec($iOne & $iTwo)
        If @error <> 0 Then
            SetError(1)
            Return -1
        EndIf
        If $iDec <> 0 Then
            $started = True
        EndIf
        If $started == True Then
            $Char = Chr($iDec)
            $strChar = $strChar & $Char
        EndIf
    Next
    
    Return $strChar
EndFunc  ;==>_HexToString

How's my riding? Dial 1-800-Wait-There

Trying to use a computer with McAfee installed is like trying to read a book at a rock concert.

Share this post


Link to post
Share on other sites



Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0