If you insist on having this trivial function in pure batch I suggest this:
@echo off
set x=somestring
set n=0
set m=255
:loop
if "!x:~%m%,1!" == "" (
set /a "m>>=1"
goto loop
) else (
set /a n+=%m%+1
set x=!x:~%m%!
set x=!x:~1!
if not "!x!" == "" goto loop
)
echo %n%
PS. You must have delayed variable expansion enabled to run this.
EDIT. Now I have made an improved version:
@echo off
set x=somestring
set n=0
for %%m in (4095 2047 1023 511 255 127 63 31 15 7 3 1 0) do (
if not "!x:~%%m,1!" == "" (
set /a n+=%%m+1
set x=!x:~%%m!
set x=!x:~1!
if "!x!" == "" goto done
)
)
:done
echo %n%
EDIT2. If you have a C compiler or something on your system you can create the programs you need and miss on the fly if they don't exist. This method is very general. Take string length as an example:
@echo off
set x=somestring
if exist strlen.exe goto comp
echo #include "string.h" > strlen.c
echo int main(int argc, char* argv[]) { return strlen(argv[1]); } >> strlen.c
CL strlen.c
:comp
strlen "%x%"
set n=%errorlevel%
echo %n%
You have to set up PATH, INCLUDE and LIB appropriately. This too can be done on the fly from the batch script. Even if you don't know whether you've got a compiler or don't know where it is you can search for it in your script.