From 1ecb4bbe7078618b8a3f80c420a320f5f86445e2 Mon Sep 17 00:00:00 2001 From: Ian Jauslin Date: Tue, 26 Sep 2023 13:01:00 -0400 Subject: [PATCH] Python script to convert bin to txt and back --- scripts/convert_bin | 70 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100755 scripts/convert_bin diff --git a/scripts/convert_bin b/scripts/convert_bin new file mode 100755 index 0000000..5b49d61 --- /dev/null +++ b/scripts/convert_bin @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 + +import sys +import struct +import re + +def print_usage(): + print("usage: convert_bin ") + +if len(sys.argv)!=5: + print_usage() + sys.exit(-1) + +if sys.argv[1]=="bin2txt": + direction="bin2txt" +elif sys.argv[1]=="txt2bin": + direction="txt2bin" +else: + print_usage() + sys.exit(-1) + +if direction=="txt2bin": + inf=open(sys.argv[2],"r") + out=open(sys.argv[3],"wb") +elif direction=="bin2txt": + inf=open(sys.argv[2],"rb") + out=open(sys.argv[3],"w") + +K=int(sys.argv[4]) + +counter=0 + +if direction=="txt2bin": + # read + entries={} + for line in inf.readlines(): + # remove double spaces + line=re.sub(' *',' ',line) + # remove initial spaces + line=re.sub('^ ','',line) + nums=line.split(" ") + kx=int(nums[0]) + ky=int(nums[1]) + Re=float(nums[2]) + im=float(nums[3]) + entries[str(kx)+","+str(ky)]=[Re,im] + # write + for kx in range(0,K+1): + for ky in range(-K,K+1): + # ignore kx<0 + if (kx>0 or (kx==0 and ky>0)): + # print if exists + if str(kx)+","+str(ky) in entries: + out.write(struct.pack('dd',entries[str(kx)+","+str(ky)][0],entries[str(kx)+","+str(ky)][1])) + else: + # otherwise 0 + out.write(struct.pack('dd',0.,0.)) + + +elif direction=="bin2txt": + for kx in range(0,K+1): + for ky in range(-K,K+1): + # ignore kx<0 + if (kx>0 or (kx==0 and ky>0)) : + entry=struct.unpack('dd',inf.read(16)) + print(kx,ky,entry[0],entry[1],file=out) + +inf.close() +out.close() +