Convert Decimal to Binary Vector

前端 未结 4 815
暗喜
暗喜 2021-01-05 01:13

I need to convert a Decimal Number to a Binary Vector

For example, Something like this:

  length=de2bi(length_field,16);

Unfortunat

4条回答
  •  粉色の甜心
    2021-01-05 01:49

    Here's a solution that is reasonably fast:

    function out = binary2vector(data,nBits)
    
    powOf2 = 2.^[0:nBits-1];
    
    %# do a tiny bit of error-checking
    if data > sum(powOf2)
       error('not enough bits to represent the data')
    end
    
    out = false(1,nBits);
    
    ct = nBits;
    
    while data>0
    if data >= powOf2(ct)
    data = data-powOf2(ct);
    out(ct) = true;
    end
    ct = ct - 1;
    end
    

    To use:

    out = binary2vector(12,6)
    out =
         0     0     1     1     0     0
    
    out = binary2vector(22,6)
    out =
         0     1     1     0     1     0
    

提交回复
热议问题