2010-04-22 62 views
10

我有一个整数数组:整数数组二进制数组

a=[3,4,5,6,7]; 

我想将它与每个四个比特转换为二进制数组。对于上述整数数组我想获得以下二进制数组:

abinary=[0,0,1,1, 0,1,0,0, 0,1,0,1, 0,1,1,0, 0,1,1,1]; 

有没有快速的方法来做到这一点?

回答

16

Matlab具有内置函数DEC2BIN。它创建一个字符数组,但很容易将其转换回数字。

%# create binary string - the 4 forces at least 4 bits 
bstr = dec2bin([3,4,5,6,7],4) 

%# convert back to numbers (reshape so that zeros are preserved) 
out = str2num(reshape(bstr',[],1))' 
+0

非常感谢乔纳斯! ;) – asel 2010-04-22 01:59:38

4

可以使用BITGET功能:

abinary = [bitget(a,4); ... %# Get bit 4 for each number 
      bitget(a,3); ... %# Get bit 3 for each number 
      bitget(a,2); ... %# Get bit 2 for each number 
      bitget(a,1)];  %# Get bit 1 for each number 
abinary = abinary(:)';  %'# Make it a 1-by-20 array 
+0

我甚至不知道bitget。尽管如此,为了能够使用它来创建任意数量的位,我会做一个循环来构建临时组织。无论如何。 – Jonas 2010-04-25 03:16:57

1

逾期答案,我知道,但是MATLAB有一个函数来做到这一点直接de2bi

out = de2bi([3,4,5,6,7], 4, 'left-msb'); 
+0

'de2bi'仅在[通讯系统工具箱](https://uk.mathworks.com/help/comm/ref/de2bi.html)中可用。 [数据采集工具箱]中存在一个类似的函数'decimalToBinaryVector'(https://uk.mathworks.com/help/daq/ref/decimaltobinaryvector.html)。 – nekomatic 2017-12-08 16:20:07