【问题标题】:How to multiply two string binary numbers from txt file如何将txt文件中的两个字符串二进制数相乘
【发布时间】:2020-02-24 17:47:37
【问题描述】:

Python 绝对初学者

给定一个 .txt 文件,包含 1000 行的以下数据

11010101    10101010 
10101010    10101010
10101000    10101010

空格由制表符分隔。我需要将两个二进制数相乘,然后将数据格式化为1000x16 矩阵,例如:

[[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]].

我的代码(到目前为止):

with open(‘file.txt’, ‘r’) in f:  
    dataset= f.read()
    dataset= f.split(’/t’)

在此之后,我只是不知道该怎么做。

任何帮助将不胜感激。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    你可以试试这个代码:

    result=[]
    with open("file.txt", "r") as f:  
        dataset= f.readline()
        while dataset:
            t=dataset.split("\t")
            x=bin(int(t[0],2)*int(t[1],2))
            x=x[2:]
            #if length of result is less than 16 
            if(len(x)<16):
                req=16-len(x)
                y=""
                for i in range(0,req,1):
                    y=y+'0'
                y=y+x
                x=y
            result.append(list(x))    
            dataset=f.readline()
    
    print(result)       
    
    

    (对于 python 3.7.4)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2019-07-19
      • 2020-08-16
      • 2016-01-17
      • 1970-01-01
      • 2016-05-08
      • 2010-10-15
      相关资源
      最近更新 更多