there's a sample input file as follows(input1.txt)
(For your information, 4'hF
means its value is 15 by decimal and it is binary 4 bits and its value is 1111
as binary per each bit.
So, 4'hF
is same as 4'b1111
)
{pDHY_es[3:0]} = 4'hF;
{pDHY_asq,1'b0,pDHY_qr,1'b1} = 4'hB;
{pQHY_yd,pRTY_a[2:0]} = 4'h5;
{1'b0,1'b0,pDSY_qr,pDNR_pf} = 4'h3;
{pQHT_yd[1:0],pDRY_pf,pTUCF_xlck} = 4'h9;
and What I want to do is to convert all the elements inside bracket(that starts with the letter'p') into its bit-assigned value. So In this case, the output would be as follows(output.txt)
pDHY_es[3:0] = 4'b1111;
pDHY_asq = 1'b1;
pDHY_qr = 1'b1;
pQHT_yd = 1'b0;
pRTY_a[2:0] = 3'b101;
pDSY_qr = 1'b1;
pDNR_pf = 1'b1;
pQHY_yd[1:0] = 2'b10;
pDRY_pf = 1'b0;
pTUCF_xlck = 1'b1;
To sum up, What I want to do is
1.extract all the element inside bracket that starts with the letter'p'.
2.put the value of each element into its bit-assigned form.
I've thought about using hex to binary converting function as follows: Convert hex to binary but Itself doesn't seem to meet what I need:
Parse the lines with split()
and strip()
inp = """{pDHY_es[3:0]} = 4'hF;
{pDHY_asq,1'b0,pDHY_qr,1'b1} = 4'hB;
{pQHY_yd,pRTY_a[2:0]} = 4'h5;
{1'b0,1'b0,pDSY_qr,pDNR_pf} = 4'h3;
{pQHT_yd[1:0],pDRY_pf,pTUCF_xlck} = 4'h9;"""
def convertBitpattern(s: str):
numBits, bits = s.split("'")
numBits = int(numBits)
return numBits, format(int(bits[1:], 16 if bits[0] == 'h' else 2), f"0{numBits}b")
def getNumbits(field):
numBits = 1
isField = False
if field[0] in '0123456789':
numBits, _ = convertBitpattern(field)
else:
isField = True
parts = field.split('[')
if len(parts) == 2:
numBits = int(parts[1].split(':')[0])+1
return isField, numBits
for line in inp.split('\n'):
fields, bitpattern = list(map(lambda x: x.strip().strip('{};'), line.split('=')))
_, bits = convertBitpattern(bitpattern)
for field in fields.split(','):
isField, numBits = getNumbits(field)
fieldBits, bits = bits[:numBits], bits[numBits:]
if isField:
print(f"{field:15} = {numBits}'b{fieldBits};")
Output
pDHY_es[3:0] = 4'b1111;
pDHY_asq = 1'b1;
pDHY_qr = 1'b1;
pQHY_yd = 1'b0;
pRTY_a[2:0] = 3'b101;
pDSY_qr = 1'b1;
pDNR_pf = 1'b1;
pQHT_yd[1:0] = 2'b10;
pDRY_pf = 1'b0;
pTUCF_xlck = 1'b1;