【发布时间】:2011-02-10 20:59:26
【问题描述】:
我有一个整数数组:
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];
有什么快速的方法吗?
【问题讨论】:
我有一个整数数组:
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];
有什么快速的方法吗?
【问题讨论】:
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))'
【讨论】:
你可以使用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
【讨论】:
我知道一个迟到的答案,但 MATLAB 有一个函数可以直接做到这一点de2bi
out = de2bi([3,4,5,6,7], 4, 'left-msb');
【讨论】:
de2bi 仅在 Communications System Toolbox 中可用。 Data Acquisition Toolbox中存在类似的函数decimalToBinaryVector。