Reputation: 648
In my batch file, I am trying to convert a string (%input%
) to binary and save the result in a batch variable %varBinary%
. My attempt:
for /f "delims=" %%a in ( ' powershell " [System.Text.Encoding]::UTF8.GetBytes(/"%_input%"/) | %{ [System.Convert]::ToString($_,2).PadLeft(8,'0') } " ' ) do set "varBinary=%%a"
echo.%varBinary%
echo."%varBinary%"
echo "%varBinary%"
echo %varBinary%
Output of %varBinary%
is always empty. What is wrong here? And how to convert back the Binary to the original string so that it works? Because that didn't work either.
For example, hello should be 0110100001100101011011000110110001101111.
Upvotes: 0
Views: 1594
Reputation: 14370
You were close, but you missed a few characters that needed to be escaped.
First, powershell (and most other things) uses \
to escape quotes, not /
. Second, in batch, plain %
need to be escaped by using %%
instead. (On a side note, you would normally have to escape the |
, but you don't have to here because it's in a quoted string.)
Finally, if you want to build the string and not just return the binary of the last character, you're going to have to enable delayed expansion and concatenate each line of the output.
@echo off
setlocal enabledelayedexpansion
set /p "_input=Input: "
for /f "delims=" %%A in ('powershell "[System.Text.Encoding]::UTF8.GetBytes(\"%_input%\") | %%{[System.Convert]::ToString($_,2).PadLeft(8,'0')}"') do set "varBinary=!varBinary!%%A"
echo.!varBinary!
echo."!varBinary!"
echo "!varBinary!"
echo !varBinary!
Upvotes: 2