我有一個整數數組:整數數組二進制數組
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
我甚至不知道bitget。儘管如此,爲了能夠使用它來創建任意數量的位,我會做一個循環來構建臨時組織。無論如何。 – Jonas 2010-04-25 03:16:57
逾期答案,我知道,但是MATLAB有一個函數來做到這一點直接de2bi
out = de2bi([3,4,5,6,7], 4, 'left-msb');
'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
非常感謝喬納斯! ;) – asel 2010-04-22 01:59:38