2016-01-29 36 views
5

Come posso convertire stringa in esadecimale nello script batch DOS? Ad esempio, convertire "abcd" in "61626364". Poiché, 'a' è 0x61 ...Script DOS batch per convertire stringa 2 esadecimale

Ho cercato di trovare una soluzione dal web, un giorno, ma non riuscivo a trovare la risposta.

+0

Dubito che ci sia una soluzione con un solo un file batch. Sarebbe facile con PowerShell se questa è un'opzione. –

risposta

3
:stringToHex 
@echo off 
del tmp.hex >nul 2>nul 
del tmp.str >nul 2>nul 
if "%~1" equ "" (
    echo no string passed 
    exit /b 1 
) 
echo|set /p=%~1 >tmp.str 
::(echo(%~1)>tmp.str 
rem certutil -dump tmp.str 
certutil -encodehex tmp.str tmp.hex >nul 
setlocal enableDelayedExpansion 
set "hex_str=" 
for /f "usebackq tokens=2 delims= " %%A in ("tmp.hex") do (
    set "line=%%A" 
    set hex_str=!hex_str!!line:~0,48! 
    set hex_str=!hex_str: =! 

) 
set hex_str=%hex_str:~0,-2% 
echo !hex_str! 

!! Ricordare che l'editor di stackoverflow potrebbe danneggiare il carattere di tabulazione. tokens=2 delims= " ci dovrebbe essere il singolo TAB dopo le eliminazioni.

richiede la stringa passata come argomento. Dai un'occhiata anche alla funzione :hexDump di debnham che puoi utilizzare al posto di certutil.

5
@echo off 
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 %hex% 

Esempio di stampa:

C:\> test.bat abcd 
61626364 
+0

cool :-) e più semplice di certutil. – npocmaka