Integer array to binary array

前端 未结 3 2064
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 09:45

I have an integer array:

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

I want to convert it to a binary array with four bits each. For the above integer array I would lik

相关标签:
3条回答
  • 2020-12-30 09:50

    You can use the BITGET function:

    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 讨论(0)
  • 2020-12-30 10:07

    Matlab has the built-in function DEC2BIN. It creates a character array, but it's easy to turn that back to numbers.

    %# 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 讨论(0)
  • 2020-12-30 10:13

    A late answer I know, but MATLAB has a function to do this directly de2bi

    out = de2bi([3,4,5,6,7], 4, 'left-msb');
    
    0 讨论(0)
提交回复
热议问题