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!
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!
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
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
P.S. More common answer provided here: dec2base with independent bits/digits calculation
Yet another way: Use "bitget":
data = 14
out = bitget (data, 4:-1:1)
out =
1 1 1 0
© 2022 - 2024 — McMap. All rights reserved.