Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOS Batch script to convert string 2 hex

How can I convert sring to hex in DOS Batch script? For example, convert "abcd" to "61626364". Since, 'a' is 0x61...

I tried to find a solution from web, a day, but could not find my answer.

like image 743
Mannsik Chung Avatar asked Jan 29 '16 04:01

Mannsik Chung


2 Answers

@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%

Output example:

C:\> test.bat abcd
61626364
like image 97
Aacini Avatar answered Sep 18 '22 23:09

Aacini


: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!

!!Mind that stackoverflow editor might corrupt tab character.tokens=2 delims= " there should be single TAB after delims.

requires the string passed as an argument.Take a look also at debnham's :hexDump function which you can use instead of certutil.

like image 38
npocmaka Avatar answered Sep 19 '22 23:09

npocmaka