在 cmd.exe 批处理文件中格式化十六进制序列

Format a hexadecimal sequence in a cmd.exe batch file

在 Windows cmd 脚本(又名 bat 脚本)中,我有一个 FOR /L loop from 1 to 8, where I need to do a bit shift and somehow format a variable as a hexadecimal number (which if you ask, is a single CPU identifier bit to feed into /AFFINITY).

我不知道最后一步该怎么做。这是我的 loop.cmd 文件:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%i IN (1,1,8) DO (
    SET /A "J=1<<%%i"
    ECHO %%i and !J!
)

除了格式化十六进制数字外,它什么都做:

1 and 2
2 and 4
3 and 8
4 and 16
5 and 32
6 and 64
7 and 128
8 and 256

预期输出为:

1 and 2
2 and 4
3 and 8
4 and 10
5 and 20
6 and 40
7 and 80
8 and 100

如何格式化十六进制数?

@echo off
setlocal enabledelayedexpansion
set x=2
set n=1
set /a result=n
for /l %%a in (1,1,10) do (
  set /a result*=x
  if "!result:~0,1!"=="1" set result=!result:16=10!
  echo %%a and !result!
)

输出:

1 and 2
2 and 4
3 and 8
4 and 10
5 and 20
6 and 40
7 and 80
8 and 100
9 and 200
10 and 400
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%i IN (1,1,8) DO (
    SET /A "J=1<<%%i"
    CALL :DECTOHEX J
    ECHO %%i and !J!
)
GOTO :EOF

:DECTOHEX VAR
SET "DEC=!%1!"
SET "HEX="
:NEXT
    SET /A DIGIT=DEC%%16, DEC/=16
    SET "HEX=%DIGIT%%HEX%"
IF %DEC% NEQ 0 GOTO NEXT
SET "%1=%HEX%"
EXIT /B

编辑回复评论

当移位值只有一位时,先前的解决方案可以正常工作,如问题中所述。如果移位后的值可能有几位,则需要进行更通用的十进制到十六进制转换,如下所示:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

REM DEFINE THE HEXA DIGITS
SET "HEXA=0123456789ABCDEF"

FOR /L %%i IN (1,1,8) DO (
    SET /A "J=3<<%%i"
    CALL :DECTOHEX J
    ECHO %%i and !J!
)
GOTO :EOF

:DECTOHEX VAR
SET "DEC=!%1!"
SET "HEX="
:NEXT
    SET /A DIGIT=DEC%%16, DEC/=16
    SET "HEX=!HEXA:~%DIGIT%,1!%HEX%"
IF %DEC% NEQ 0 GOTO NEXT
SET "%1=%HEX%"
EXIT /B