我有一个整数数组:
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];
有没有快速的方法呢?
答案 0 :(得分: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))'
答案 1 :(得分: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
答案 2 :(得分:1)
我知道的答案很晚,但MATLAB有一个直接执行此功能de2bi
out = de2bi([3,4,5,6,7], 4, 'left-msb');