问题
I have this so far:
data = 14
out = dec2bin(data, 4)
which gives:
out = 1110
But I want to get binary number in this format:
out = [1 1 1 0]
Thanks for help!
回答1:
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
回答2:
Yet another way: Use "bitget":
data = 14
out = bitget (data, 4:-1:1)
out =
1 1 1 0
回答3:
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
dec2binat all, you can definede2bifunction 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
来源:https://stackoverflow.com/questions/29274368/decimal-to-binary-as-double-type-array-not-string