将字符串转换为字节数组并在批处理文件中添加值

时间:2017-09-19 18:12:04

标签: windows batch-file

输入字符串看起来类似于:S214FE0420FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00

我想删除前两位数字和后两位数字。 然后我想成对地将剩余的数字相加(十六进制的字节数)。 例如:14 + FE + 04 + 20 + FF + ...

最好的方法是什么?

感谢。

2 个答案:

答案 0 :(得分:0)

虽然你没有表现出任何努力,但我决定提供一个简单的脚本;请你下次自己尝试一下!

所以这是代码(参见所有解释性rem备注):

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_STRING=S214FE0420FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00"
if not defined _STRING set /P _STRING="" & rem // (prompt if empty constant)
set "_TRUNCL=2" & rem // (truncate this many characters from the left)
set "_TRUNCR=2" & rem // (truncate this many characters from the right)

setlocal EnableDelayedExpansion
rem // Truncate defined number of characters:
set "STRING=!_STRING:~%_TRUNCL%,-%_TRUNCR%!"
rem // Initialise pointer and buffer:
set /A "POINTER=0, BUFFER=0"
rem // Skip loop if truncated string is empty:
if not defined STRING goto :NEXT
rem // Establish loop to walk through string at every two characters:
:LOOP
rem /* Prefix pointed two characters with `0x` to be interpreted as hexadecimal
rem    number and add them to buffer; afterwards increment pointer by 2 + 1
rem    (the additional 1 is intended to ignore the last digit if there is an
rem    odd number; the 1 is subtracted later again): */
set /A "BUFFER+=0x!STRING:~%POINTER%,2!, POINTER+=3"
rem /* Check if characters are still available at the new pointer, then
rem    subtract the aforementioned 1 from the new pointer: */
if not "!STRING:~%POINTER%!"=="" set /A "POINTER-=1" & goto :LOOP
rem /* No more characters are available, so leave the loop; also subtract the
rem    aforementioned 1 from the new pointer, so it holds the string length: */
set /A "POINTER-=1"
rem // This is the point beyond the loop:
:NEXT
rem // Return the result:
echo/sum:    %BUFFER%
echo/length: %POINTER%
endlocal

endlocal
exit /B

答案 1 :(得分:0)

这是一个完全无法解决的例子,我将不提供任何帮助。

@Echo Off
SetLocal EnableDelayedExpansion
Set "input=S214FE0420FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00"
For /L %%A In (2 2 40) Do Set "output=!output!+0x!input:~%%A,2!"
Set/A output=%output:~1%
Echo(%input:~2,-2%=%output%
Timeout -1