1

The existing solutions like echo -e equivalent in Windows? provide simple methods for ASCII 32-126 and CharLib, which is quite big and thus not fit to include inside a small batch file.

Is there a simple method to write a sequence of characters represented by hex codes in 00-255 range like 05 75 9a FF to a binary file?

Community
  • 1
  • 1
Akshaya
  • 11
  • 3
  • How will you input such binary data, and how will you use it ? – Claudio Nov 19 '15 at 09:16
  • I want to create a binary file. I tried echo command. It always writes the hex code of character to the file. If I write 24 to file and hexdump the file, I should get 24 only - this is the requirement. If i use echo 24 and hexdump the file, I get 32 34 corresponding to ascii codes of '2' and '4'. I simply want to create a hexadecimal header to my image. I have a hex file and want to add a header to it like magic number. And this I have to do with the help of batch scripting. – Akshaya Nov 19 '15 at 09:28
  • What if I want to input hex values outside the range of ASCII character set? – Akshaya Nov 19 '15 at 12:45

1 Answers1

3

Writing non-ASCII codes 80-FF is tricky. I haven't seen a simple solution before so here it is.

Usage:

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

or

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

The function:

: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
wOxxOm
  • 65,848
  • 11
  • 132
  • 136