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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值