0

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.

1 Answer 1

2

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!
Sign up to request clarification or add additional context in comments.

2 Comments

Let me recommend to clear the variable varBinary before the for /F loop...
@aschipfl - the setlocal acts as a variable sandbox, so as long as this is the entire script, it can get run over and over without the need to clear %varBinary% since it gets initialized when the script starts (but if this is going to be part of something bigger, clearing it is a good idea).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.