如何在不使用循环的情况下将二进制转换为十进制? [英] How can I convert a binary to a decimal without using a loop?

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

问题描述

我有一个12位二进制文​​件,需要将其转换为十进制数.例如:

I have a 12-bit binary that I need to convert to a decimal. For example:

A = [0,1,1,0,0,0,0,0,1,1,0,0];

位1是最高有效位,位12是最低有效位.

Bit 1 is the most significant bit, Bit 12 is the least significant bit.

推荐答案

注意:该答案主要适用于无符号数据类型.要转换为带符号的类型,需要执行一些额外的步骤,请在此处中进行讨论.

Note: This answer applies primarily to unsigned data types. For converting to signed types, a few extra steps are necessary, discussed here.

bin2dec 函数是一个选项,但需要您首先将向量更改为字符串.与自己计算数字相比,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)-10.然后,将所得的向量求和,得到由零和一的二进制模式表示的整数,并且数组中的第一个元素被认为是最高有效位.如果希望将第一个元素视为最低有效位,则可以执行以下操作:

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向量:

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天全站免登陆