Home > Net >  Trying to convert text into hex by calling a function within my batch file, but the hex code never g
Trying to convert text into hex by calling a function within my batch file, but the hex code never g

Time:05-06

@echo off

goto :main

 
:strg2hex
setlocal EnableDelayedExpansion

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
echo The string to hex is %hex%

set %~1=%hex%

goto :eof



:main

     echo This is the main function!
 
     ::This interprets "tiger" as a string.
     ::This will convert text "tiger" into hex with the above function.
     call :strg2hex tiger
     Echo this is text "tiger" converted into hex: %hex%

Pause

goto :eof

CodePudding user response:

in place of

set %~1=%hex%

use

endlocal&set "%~1=%hex%"&SET "hex=%hex%"

Because you are executing a setlocal, when you goto :eof, the local environment containing your changes is deleted and the original, unchanged environment is restored.

This statement works because batch parses, substitutes and then executes the command, so what is actually executed is

 endlocal&set "tiger=7469676572"&SET "hex=7469676572"

so the local environment is deleted, then the values are set.

  • Related