[Batch] Convert String to Hex

Discussion in 'Scripting' started by demon.devin, Oct 2, 2017.

  1. demon.devin

    demon.devin MDL Novice

    Oct 2, 2017
    3
    4
    0
    The following batch script will take an input string and convert it into it's hex counterpart with a comma (,) delimiter every 2nd character.

    Save this file to something like str2hex.bat

    Call it like this:
    str2hex.bat demon.devin

    Return output:
    64,65,6D,6F,6E,2E,64,65,76,69,6E

    Code:
    @echo off
    setlocal EnableDelayedExpansion
    
    :stringToHex
    rem Store the string in chr.tmp file.
    set /P "=%~1" < NUL > chr.tmp
    
    rem Create zero.tmp file with the same number of ASCII zero characters.
    for %%a in (chr.tmp) do fsutil file createnew zero.tmp %%~Za > NUL
    
    rem Compare both files with FC /B and get the differences.
    set "hex="
    for /F "skip=1 tokens=2" %%a in ('fc /B chr.tmp zero.tmp') do set "hex=!hex!%%a"
    
    del chr.tmp zero.tmp
    
    set Text=%hex%
    set output=
    
    rem Batch files don't have a LEN function.
    rem So this loop will process up to 500 chararcters by doing a substring on each.
    for /L %%I in (0,2,500) do (
        call set Letter=!Text:~%%I,2!
        rem Only process when a letter is returned.
        if not "!Letter!" == "" (
            set output=!output!,!Letter!
        ) else (
            rem Otherwise, we have reached the end.
            goto DoneProcessing
        )
    )
    
    :DoneProcessing
    rem Remove leading character.
    set output=%output:~1,999%
    echo %output%