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)