二进制转换为十进制没有使用循环 [英] Converting binary to decimal without using loop

查看:132
本文介绍了二进制转换为十进制没有使用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个12位二进制文​​件,我需要转换为十进制。

I have a 12bit binary that I need to convert to decimal.

例如。
A = [0,1,1,0,0,0,0,0,1,1,0,0];

第1位是MSB,第12位为LSB。

Bit 1 is the MSB, Bit 12 is the LSB .

我该怎么办呢?

推荐答案

函数是一种选择,但需要你的矢量首先更改为字符串。 BIN2DEC也可以相比计算自己的数目是缓慢的。下面是更快约75倍的解决方案:

The BIN2DEC function is one option, but requires you to change the vector to a string first. BIN2DEC can also be slow compared to computing the number yourself. Here's a solution that's about 75 times faster:

>> A = [0,1,1,0,0,0,0,0,1,1,0,0];
>> B = sum(A.*2.^(numel(A)-1:-1:0))

B =

        1548

要解释, A 相乘元素明智的2的幂的载体,用指数从 numel(A)-1 0 。然后将所得的矢量相加,得到由0和1的二进制图案psented整数重新$ P $,与阵列中的第一个元件被认为是最显著位。如果你想第一个元素被认为是最显著位,你可以做到以下几点:

To explain, A is multiplied element-wise by a vector of powers of 2, with the exponents ranging from numel(A)-1 down to 0. The resulting vector is then summed to give the integer represented by the binary pattern of zeroes and ones, with the first element in the array being considered the most significant bit. If you want the first element to be considered the least significant bit, you can do the following:

>> B = sum(A.*2.^(0:numel(A)-1))

B =

        774

编辑:此外,如果你有很多要转换成整数的二进制向量,上述解决方案可以方便地进行修改,所有的值转换成一个矩阵运算。假设 A 是一个N×12的矩阵,每行一个二进制向量。以下将它们全部转换为一个N×1向量整数值:

In addition, if you have a lot of binary vectors you want to convert to integers, the above solution can easily be modified to convert all the values with one matrix operation. Suppose A is an N-by-12 matrix, with one binary vector per row. The following will convert them all to an N-by-1 vector of integer values:

B = A*(2.^(size(A,2)-1:-1:0))';  % Most significant bit first
B = A*(2.^(0:size(A,2)-1))';     % Least significant bit first

另外请注意,所有上述解决方案通过在 A 看着列数自动确定在矢量的位数

Also note that all of the above solutions automatically determine the number of bits in your vector by looking at the number of columns in A.

这篇关于二进制转换为十进制没有使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆