How to Encode Text to Hexadecimal in Batch Script
When working with low-level data, debugging scripts, or preparing text for binary processing, it’s often necessary to convert readable characters into their hexadecimal representation. Hex encoding transforms each character into a numeric value, making it suitable for tasks like data obfuscation, handling special or non-printable characters, and interacting with systems that expect raw byte input.
While modern tools like PowerShell provide built-in commands for this, pure Windows Batch scripting does not offer a direct way to perform such conversions. This means you must build the logic yourself, typically by creating lookup tables and iterating through each character in a string.
In this guide, we’ll walk through how to construct a fully self-contained Batch script that converts plain text into hexadecimal using loops and variable-based arrays, giving you a deeper understanding of how data manipulation works at the command-line level.
The Logic Behind Plaintext to Hexadecimal Conversion
Computers interpret text as numbers. Specifically, "A" is 65 in decimal and 41 in hexadecimal.
Batch Script does not contain a native encode_hex() function. Therefore, the core of our script relies on mapping every allowed character to its corresponding two-digit hex value manually into memory before we process the string.
Building the Lookup Definition Array
To achieve the encoding quickly, we define dozens of variables. For example, a variable named map_A will contain the string 41. We do this for all uppercase letters, lowercase letters, numbers, and basic punctuation marks that our script needs to handle.
@echo off
setlocal enabledelayedexpansion
title Text to Hex Encoder
:: Manually mapping common characters
set "map_A=41"
set "map_B=42"
set "map_C=43"
set "map_D=44"
set "map_E=45"
set "map_F=46"
set "map_G=47"
set "map_H=48"
set "map_a=61"
set "map_b=62"
set "map_c=63"
set "map_1=31"
set "map_2=32"
set "map_3=33"
:: Handling spaces uniquely since variable names with spaces break logic
set "map_space=20"
Creating the Processing Loop
After our map is initialized horizontally in memory, we need a mechanism that tears the user's input string apart into single characters. We then use that single character to query our map.
Extracting Characters Iteratively
set "INPUT_TEXT="
set /p "INPUT_TEXT=Enter text to encode: "
set "HEX_OUTPUT="
set "ptr=0"
:CHAR_LOOP
:: Extract a single character at the current pointer index
set "char=!INPUT_TEXT:~%ptr%,1!"
:: If the extraction returns nothing, we have reached the end of the string
if "!char!"=="" goto DISPLAY_HEX
Passing Characters to the Hex Map
Inside our character loop, we evaluate the character. We must specifically check if it's a "space" before we query the map dynamically, because variables like !map_ ! cause massive syntax confusion.
:: Unique handling for the space bar
if "!char!"==" " (
set "char=space"
)
:: Dynamically build the variable name to pull the mapped hex value
set "hexval=!map_%char%!"
:: If the character isn't defined in our script, we fallback to a placeholder (??)
if not defined hexval (
set "hexval=??"
)
:: Append the parsed hex value to our growing output string
set "HEX_OUTPUT=!HEX_OUTPUT!!hexval! "
:: Advance the pointer and loop again
set /a ptr+=1
goto CHAR_LOOP
Parsing Special Characters Safely
One of the largest hurdles an entry-level batch developer confronts is validating command-line special characters. If a user tries to encode an ampersand (&) or a pipe (|), the command prompt attempts to execute them as logical operators instead of plain strings.
The Wrong Way: Unquoted Environment Variables
When you request text via set /p and then evaluate it outside of double quotes, the engine crashes on special characters before the looping even begins.
Wrong Code Example:
@echo off
set /p "INPUT_TEXT=Type something: "
:: If the user types: hello & world
if %INPUT_TEXT%==exit goto EOF
What Happens:
The script evaluates the if statement for hello, hits the &, determines that the if command is finished, and subsequently attempts to execute the word world as a standalone Windows program. A "world is not recognized as an internal or external command" error appears, terminating the script flow.
The Correct Way: Strict Delayed Expansion and Quoting
To handle inputs safely and convert them into hex without the script treating your letters as commands, you must use delayed expansion ! combined with double quotes. This instructs the CMD engine to treat the contents strictly as string literals.
Correct Code Example:
@echo off
setlocal enabledelayedexpansion
set "INPUT_TEXT="
set /p "INPUT_TEXT=Type something: "
:: Delayed expansion ! variables protect against evaluation inside an IF statement
if "!INPUT_TEXT!"=="exit" goto EOF
:: We also mapped special characters using an underscore or name to protect the definition
set "map_ampersand=26"
set "map_pipe=7C"
What Happens:
When the user types hello & world, the evaluation if "hello & world"=="exit" runs safely without severing the command. It evaluates to false, and the script seamlessly continues character looping.
Full Script Implementation
Putting the map building, spatial handling, delayed expansion protections, and character looping together yields a fully capable encoding script.
@echo off
setlocal enabledelayedexpansion
title Native Text to Hexadecimal Encoder
:: 1. Building the Hexadecimal Map
set "map_A=41" & set "map_B=42" & set "map_C=43" & set "map_D=44"
set "map_E=45" & set "map_F=46" & set "map_G=47" & set "map_H=48"
set "map_I=49" & set "map_J=4A" & set "map_K=4B" & set "map_L=4C"
set "map_M=4D" & set "map_N=4E" & set "map_O=4F" & set "map_P=50"
set "map_Q=51" & set "map_R=52" & set "map_S=53" & set "map_T=54"
set "map_U=55" & set "map_V=56" & set "map_W=57" & set "map_X=58"
set "map_Y=59" & set "map_Z=5A"
set "map_a=61" & set "map_b=62" & set "map_c=63" & set "map_d=64"
set "map_e=65" & set "map_f=66" & set "map_g=67" & set "map_h=68"
set "map_i=69" & set "map_j=6A" & set "map_k=6B" & set "map_l=6C"
set "map_m=6D" & set "map_n=6E" & set "map_o=6F" & set "map_p=70"
set "map_q=71" & set "map_r=72" & set "map_s=73" & set "map_t=74"
set "map_u=75" & set "map_v=76" & set "map_w=77" & set "map_x=78"
set "map_y=79" & set "map_z=7A"
set "map_0=30" & set "map_1=31" & set "map_2=32" & set "map_3=33"
set "map_4=34" & set "map_5=35" & set "map_6=36" & set "map_7=37"
set "map_8=38" & set "map_9=39"
set "map_space=20"
set "map_period=2E"
set "map_comma=2C"
set "map_hyphen=2D"
set "map_colon=3A"
set "map_semicolon=3B"
set "map_question=3F"
set "map_at=40"
set "map_hash=23"
set "map_dollar=24"
set "map_underscore=5F"
set "map_plus=2B"
set "map_equals=3D"
set "map_tilde=7E"
set "map_apostrophe=27"
set "map_slash=2F"
set "map_backslash=5C"
set "map_openparen=28"
set "map_closeparen=29"
:GET_INPUT
cls
echo =========================================
echo TEXT TO HEXADECIMAL ENCODER
echo =========================================
set "INPUT_TEXT="
set /p "INPUT_TEXT=Enter Text (Max 100 characters): "
if not defined INPUT_TEXT goto GET_INPUT
:: 2. Initialize the loop variables
set "HEX_OUTPUT="
set "ptr=0"
:LOOP
set "char=!INPUT_TEXT:~%ptr%,1!"
if "!char!"=="" goto DISPLAY_HEX
:: 3. Handling Problematic Chars Safely
if "!char!"==" " set "char=space"
if "!char!"=="." set "char=period"
if "!char!"=="," set "char=comma"
if "!char!"=="-" set "char=hyphen"
if "!char!"==":" set "char=colon"
if "!char!"==";" set "char=semicolon"
if "!char!"=="?" set "char=question"
if "!char!"=="@" set "char=at"
if "!char!"=="#" set "char=hash"
if "!char!"=="$" set "char=dollar"
if "!char!"=="_" set "char=underscore"
if "!char!"=="+" set "char=plus"
if "!char!"=="=" set "char=equals"
if "!char!"=="~" set "char=tilde"
if "!char!"=="'" set "char=apostrophe"
if "!char!"=="/" set "char=slash"
if "!char!"=="\" set "char=backslash"
if "!char!"=="(" set "char=openparen"
if "!char!"==")" set "char=closeparen"
:: 4. Look up in the map array
set "hexval=!map_%char%!"
:: 5. Fallback for undefined characters
if not defined hexval set "hexval=??"
:: 6. Append to Output String
set "HEX_OUTPUT=!HEX_OUTPUT!!hexval! "
set /a ptr+=1
goto LOOP
:DISPLAY_HEX
echo.
echo Original String:
echo !INPUT_TEXT!
echo.
echo Hexadecimal Encoding:
echo !HEX_OUTPUT!
echo.
pause
goto GET_INPUT
Because Batch loops evaluate individually character by character, attempting to encode a paragraph or extremely long string will run noticeably slower than native C# or Python executables. Keep encoded strings relatively short when dealing directly with Command Prompt mapping arrays. Additionally, certain shell metacharacters (!, ^, &, |, <, >, ", %) cannot be reliably captured or compared under delayed expansion and are best avoided in input strings.
Conclusion
Encoding strings to Hexadecimal in a purely native Batch Script is a tremendous exercise that perfectly illustrates the implementation of manual environment mapping and iterative string parsing. By replacing special instances, such as spaces and punctuation, with named string keys, and wrapping values in strictly delayed expansions (!), your standalone script behaves as a solid, portable conversion utility unaffected by logical operator glitches.