binary模块的match 与 matches函数

本文对比了binary:match与binary:matches两个函数的功能差异。前者仅匹配首次出现,后者则匹配所有符合规则的项。两者均遵循从左至右的遍历原则,优先选取最长的匹配项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

binary:match函数与binary:matches函数的匹配规则一致,即

匹配字符串只做一次遍历字符,然后根据当前字符去待匹配字符列表寻找符合条件的,优先选择长度最长的纳入结果

结果格式为{pos, length}

 

两者区别是:

match匹配第一项

matches匹配所有满足的匹配项

import re import random #TODO : Change support for 0b to 0h inputs. with open('tb_systolic_array.sv', 'r') as file: content = file.read() """ A function to convert from float to binary """ def float_to_binary(num : float, precision: int = 23) -> str: whole, decimal = str(num).split(".") whole = int(whole) decimal = float(f"0.{decimal}") #Convert the whole number part into binary whole_bin = bin(whole).replace("0b", "") decimal_bin = [] while decimal and len(decimal_bin) < precision: decimal *= 2 bit = int(decimal) decimal_bin.append(str(bit)) decimal -= bit return whole_bin + "." + "".join(decimal_bin) """ Normalizing the floating point number """ def normalize(num : str) -> list: temp = num.split(".") temp = int(temp[0]) exp = -1 while temp != 0: temp //= 10 exp += 1 num = num.replace(".","") num = num[1:24] exp += 127 exp = bin(exp).replace("0b", "") return [num, exp] def float_to_fp32(num : float) -> int: sign_bit = 0 if (num < 0): sign_bit = 1 y = normalize(float_to_binary(num)) return int(str(sign_bit) + str(y[1]) + y[0]) if __name__ == "__main__": # Find all occurrences of in_a and in_b assignments matches = re.findall(r"in_a = 32'b[01]+; in_b = 32'b[01]+;", content) for match in matches: r1 = float_to_fp32(random.uniform(0, 100)) r2 = float_to_fp32(random.uniform(0, 50)) in_a_value, in_b_value = r1, r2 new_assignment = f"in_a = 32'b{in_a_value}; in_b = 32'b{in_b_value};" content = content.replace(match,new_assignment,1) # Write the modified content back to the file with open('tb_systolic_array_2.sv', 'w') as file: file.write(content)解释上述代码
最新发布
03-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值