Decimal to binary as double type array, not string

后端 未结 3 783
半阙折子戏
半阙折子戏 2020-12-07 03:15

I have this so far:

data = 14
out = dec2bin(data, 4)

which gives:

out = 1110

But I want to get binary num

相关标签:
3条回答
  • 2020-12-07 03:49

    You're looking for de2bi, bi2de functions.

    It requires the Communication Systems Toolbox.

    If you don't have it, you can work define these functions at the begining of your code as:

    de2bi = @(x) dec2bin(x)>48;
    bi2de = @(x) x*2.^(size(x,2)-1:-1:0)';
    

    Test:

    dec = 1:10
    bin = de2bi(dec)
    dec = bi2de(bin)
    

    Output:

    dec =
    
        1    2    3    4    5    6    7    8    9   10
    
    bin =
    
      0  0  0  1
      0  0  1  0
      0  0  1  1
      0  1  0  0
      0  1  0  1
      0  1  1  0
      0  1  1  1
      1  0  0  0
      1  0  0  1
      1  0  1  0
    
    dec =
    
        1
        2
        3
        4
        5
        6
        7
        8
        9
       10
    

    P.S. If, by some reason, you don't want to use dec2bin at all, you can define de2bi function as:

    In Matlab/Octave:

    de2bi = @(x)  2.^[(floor(log2(max(x(:)))):-1:1),0];
    de2bi = @(x) rem(x(:),2*de2bi(x))>(de2bi(x)-1);
    

    In Octave only (as far as Octave allows default values for anonymous functions):

    By default returns the same as in the previous example, but optional bit position parameter is available:

    de2bi = @(dec,bit=[(1+floor(log2(max(dec(:))))):-1:2, 1]) rem(dec(:),2.^bit)>(2.^(bit-1)-1);
    
    %Call examples:
    x=0:10; 
    n=3:-1:1;
    de2bi(x)
    de2bi(x,n)   % returns only the three least significant bits
    
    0 讨论(0)
  • 2020-12-07 04:00

    You're looking for de2bi with the 'left-msb' option.

    data = 14
    out = de2bi(data, 4,'left-msb')
    

    Which requires the Communication Systems Toolbox though. Alternatively use your original approach with the fundamental dec2bin with the following addition:

    data = 14
    out = double( dec2bin(data, 4) ) - 48
    

    out =
    
         1     1     1     0
    
    0 讨论(0)
  • 2020-12-07 04:02

    Yet another way: Use "bitget":

    data = 14
    out = bitget (data, 4:-1:1)
    out =
       1   1   1   0
    
    0 讨论(0)
提交回复
热议问题