byaby
byaby

Reputation: 23

BATCH- binary with for

I have to make a script that has to calculate the mask and the net, so I'm trying a script with for but it can not convert the IP to binary. I think I'm not using the variables right.

Any ideas?

@echo off  
setlocal enabledelayedexpansion  

set var=%1  
set /p var=Introduce la ip:   

for /F "tokens=1 delims=." %%a in ("%var%") do (  

    echo %%a  
    set "vara=%%a"  
    :binario  
    set bin=2  
    set /a resto=%vara%%%bin%  
    set /a a=%vara%/%bin%  
    set resultado=%resto%%resultado%  
    if %vara% GTR 0 (goto binario)  
    echo %resultado%  
    goto siguiente  
    )  
    :siguiente  
for /F "tokens=2 delims=." %%b in ("%var%") do (  
    echo %%b  
    )  
for /F "tokens=3 delims=." %%c in ("%var%") do (  
    echo %%c  
    )  
for /F "tokens=4 delims=." %%d in ("%var%") do (  
    echo %%d  
    )  

goto fin  

:vacio  
echo Error!  
goto fin  

:fin  
pause 

Upvotes: 1

Views: 683

Answers (1)

rojo
rojo

Reputation: 24466

You've got a few minor problems that I see. You set var=%1 but you never check to see whether %1 was supplied before doing set /p var=Enter an IP:. You never call or goto :vacio. As I commented above, modulos within batch scripts need to be written as %% to prevent evaluation as variable chararacters. You don't need % in var names in set /a commands, and you can combine multiple set /a statements with a comma. So instead of

set /a resto=%vara%%%bin%
set /a a=%vara%/%bin%

(which is wrong anyway -- I'll get to that in a minute), I suggest this would be more understandable and maintainable:

set /a resto = vara %% bin, numero = vara / bin

The biggest problem is that you appear to be trying to modify %%a. Don't do that.

If I were you, I would move the decimal to binary conversion to a subroutine, and call it for each octet. Try this:

@echo off  
setlocal enabledelayedexpansion  

set IP=%1

if "%IP%"=="" set /p "IP=Introduce la ip: "

set idx=0

for %%a in (%IP:.= %) do (

    if %%a lss 0 goto vacio
    if %%a gtr 255 goto vacio
    if !idx! gtr 3 goto vacio

    set /P "=%%a = "<NUL
    call :dec2bin bin[!idx!] %%a
    set /a idx += 1
)

echo %bin[0]%.%bin[1]%.%bin[2]%.%bin[3]%
goto fin

:dec2bin <var_para_definir> <numero>
setlocal enabledelayedexpansion
set numero=%~2
set bin=
for /L %%I in (1,1,8) do (
    set /a bit = numero %% 2, numero /= 2
    set bin=!bit!!bin!
)
echo %bin%
endlocal & set "%~1=%bin%"
goto :EOF

:vacio  
echo Error!  
goto fin  

:fin  
pause

For more information about using call as a function that returns a value, see this page.

Upvotes: 1

Related Questions