KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Generating a Hex Dump from string of data
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: May 4, 2018

Here is a utility method that will take a string and generate a Hex Dump:

//---------------------------------------------------------------------------------
// Name: HEXDUMP
// Description: Method will take in a string and extract it as a HEX DUMP string
//
// Parameters:
// $1 (TEXT) - String of data
//
// Output:
// $0 (TEXT) - HEX DUMP String
// --------------------------------------------------------------------------------
C_TEXT($1;$str;$strHexAddr;$strChr;$strAChar;$strHexDump;$CR;$LF)
C_TEXT($0;$output)
C_LONGINT($hexCnt;$bytesCnt;$charCode;$i;$j)


If (Count parameters=1)

 $str:=$1

 $hexCnt:=0
 $bytesCnt:=0
 $strHexAddr:=""
 $strChr:=""
 $strAChar:=""
 strHexDump:=""
 $CR:=Char(Carriage return)
 $LF:=Char(Line feed)

 For ($i;1;Length($str))
    If ($hexCnt=0)
     $hexCnt:=1
     $strHexAddr:=Substring(String($i-1;"&$00000000");2)+" "
    End if

    $charCode:=character code($str[[$i]])
    $strChr:=$strChr+Substring(String(Character code($str[[$i]]);"&$");2)+" "

    if (($charCode>32)&($charCode<127))
     $strAChar:=$strAChar+$str[[$i]]
    Else
     $strAChar:=$strAChar+"."
    End if

    $bytesCnt:=$bytesCnt+1

    If ($bytesCnt=16)
      $hexCnt:=0
      $bytesCnt:=0
      $strHexDump:=$strHexDump+$strHexAddr+" "+$strChr+" "+$strAChar+$CR+$LF
      $strHexAddr:=""
      $strChr:=""
      $strAChar:=""
    End if

    If ($i=Length($str))
      For ($j;$bytesCnt+1;16)
       $strChr:=$strChr+"00"+" "
       $strAChar:=$strAChar+"."
      End for

      $strHexDump:=$strHexDump+$strHexAddr+" "+$strChr+" "+$strAChar+$CR+$LF
     End if

  End for

  $output:="Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"+$CR+$LF
  $output:=$output+"=========================================================="+$CR+$LF
  $0:=$output+$strHexDump

End if


Here is an example:

C_TEXT($text;$output)

$text:="The folowing text in 4D..."
$output:=HEXDUMP ($text)