Python實現MATLAB bi2de函數

Python實現MATLAB bi2de函數
主要功能是將二進制數組轉爲十進制數
此文章用Python實現了bi2de函數的第一個功能
MATLB解釋

%BI2DE Convert binary vectors to decimal numbers.
% D = BI2DE(B) converts a binary vector B to a decimal value D. When B is
% a matrix, the conversion is performed row-wise and the output D is a
% column vector of decimal values. The default orientation of the binary
% input is Right-MSB; the first element in B represents the least
% significant bit.

其中B是矩陣,按照行的形式轉換爲D,D是一個列向量
默認二進制數組是從右輸入的,也就是說二進制數組第一個值是最小的
二進制數從右往左讀
Python代碼

'''
@Author: YvonneMYF
@Date: 2020-03-04 22:03:14
@LastEditTime: 2020-03-04 22:28:01
'''
import numpy as np


def bi2de(binary):
    # 與matlab bi2de函數基本功能相同
    # 將二進制數組轉化爲十進制數
    # 二進制數組內從右向左讀
    bin_temp = 0
    bin_res = np.zeros(len(binary), dtype=int)
    for i in range(len(binary)):
        for j in range(len(binary[i])):
            bin_temp = bin_temp + binary[i][j] * (2 ** j)
        bin_res[i] = bin_temp
        bin_temp = 0
    return bin_res
    
# 測試   
x = np.reshape(np.random.randint(0, 2, 8), (2,4))
print(x)
y = bi2de(x)
print(y)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章