我正在尝试创建一个由 116 个随机字符组成的字符串,我不擅长理解批处理文件,但我设法创建一个从 0 到 15 的随机数 rand 以从
hex_chars=0123456789ABCDEF
获取元素
但是当我尝试从字符串中获取并输出元素时,我不断遇到问题。
@echo off
setlocal enabledelayedexpansion
REM Define the length of the random hex string
set "hex_length=116"
REM Initialize the hex characters
set "hex_chars=0123456789ABCDEF"
REM Variable to store the random hex string
set "random_hex="
REM Loop until the required length is reached
for /L %%i in (1,1,%hex_length%) do (
REM Generate a random number between 0 and 15
set /a "rand=((%random% * %random% + %random% %% 281 * %%i) + %time:~-2%) %% 16"
echo !rand!
REM Returns 0 every time
echo !hex_chars:~%rand%,1!
REM Returns 0123456789ABCDEFrand every time
echo !hex_chars:~!rand!,1!
REM Get the hex character from hex_chars based on the random number
set random_hex=%random_hex%!hex_chars:~%rand%,1!
)
REM Output the random hex string
echo Random Hex (116 chars): !random_hex!
endlocal
pause
我想通过 for 获取 hex_string 元素,但我不知道如何正确地做到这一点
我尝试更改 % 和 !和 !hex_chars 中的 ^ 符号:~!rand!,1!
别担心。变量的管理是批处理文件中最令人困惑的点之一,特别是延迟扩展功能。要记住的两个要点是:
当变量的值在相同命令中发生变化时,您不能在命令中使用 %standard% 扩展,就像在 FOR 循环中一样;你必须使用!延迟!而是扩张。关于这一点,这个网站上有很多问题/答案;我建议您阅读这个答案或这个答案。
相同扩展字符(%
或!
)进行嵌套
;您只能将 %normal% 扩展放在 !delayed! 内一。例如:
echo !hex_chars:~!rand!,1!
是错误的。您必须使用“技巧”来避免此类嵌套,如此处或此处所述。
%random%
和
%time:~-2%
扩展必须是
!random!
和
!time:~-2!
(如果您希望它们在每次迭代中发生变化)。应用第二点,最终的工作代码是这样的:
@echo off
setlocal enabledelayedexpansion
REM Define the length of the random hex string
set "hex_length=116"
REM Initialize the hex characters
set "hex_chars=0123456789ABCDEF"
REM Variable to store the random hex string
set "random_hex="
REM Loop until the required length is reached
for /L %%i in (1,1,%hex_length%) do (
REM Generate a random number between 0 and 15
set /a "rand=((!random! * !random! + !random! %% 281 * %%i) + !time:~-2!) %% 16"
rem echo !rand!
REM Get the hex character from hex_chars based on the random number
for %%r in (!rand!) do set "random_hex=!random_hex!!hex_chars:~%%r,1!
)
REM Output the random hex string
echo Random Hex (116 chars): %random_hex%
endlocal
pause