将非ASCII字符代码写入二进制文件

时间:2015-11-19 08:29:50

标签: batch-file

echo -e equivalent in Windows?这样的现有解决方案为ASCII 32-126和CharLib提供了简单的方法,这种方法非常大,因此不适合包含在小批量文件中。

是否有一种简单的方法可以将由05 75 9a FF等00-255范围内的十六进制代码表示的字符序列写入二进制文件?

1 个答案:

答案 0 :(得分:3)

编写非ASCII代码80-FF很棘手。我之前没有见过一个简单的解决方案。

用法:

@echo off
call :writeHex "30 31 32 9F 00 a0 FF" "outputfile.bin"
exit /b

@echo off
call :writeHex 3031329F00a0FF "outputfile.bin"
exit /b

功能:

:writeHex
rem Usage:
rem call :writeHex 3031329F00a0FF "outputfile.bin"
rem call :writeHex "30 31 32 9F 00 a0 FF" "outputfile.bin"
    findstr /r "^[^a-z]*:::" "%~f0" >"%temp%\writebin.vbs"
    cscript //nologo "%temp%\writebin.vbs" "%~1" "%~2"
    del "%temp%\writebin.vbs"
    exit /b

    :::hx = replace(wscript.arguments(0)," ","")
    :::file = wscript.arguments(1)
    :::
    :::length = len(hx)/2 : if length mod 2 then hx = hx & "00"
    :::
    :::s = ""
    :::for i=1 to len(hx) step 4
    :::  s = s & chrW(clng("&H" & mid(hx,i,2)) + clng("&H" & mid(hx,i+2,2)) * 256)
    :::next
    :::
    :::typeBin = 1 : typeText = 2 : bOverwrite = 2
    :::with CreateObject("ADODB.Stream")
    :::  .type = typeText : .open : .writeText s : .saveToFile file, bOverwrite : .close
    :::  .type = typeBin : .open : .loadFromFile file : .position = 2 : data = .read(length)
    :::  .position = 0 : .write data
    :::  .position = length : .setEOS
    :::  .saveToFile file, bOverwrite
    :::  .close
    :::end with