MATLAB: How to convert decimal into binary

binarydecimal

Hello,
I need to convert n-bit decimal into 2^n bit binary number. I do not have much idea. Can anybody help me please?

Best Answer

This code shows '11111111' only, because you overwrite the output in each iteration:
n= 8;
for i = 0:2^n-1
x = dec2bin(i,8);
end
Therefore x contains the last value only: dec2bin(2^n-1, 8).
Better:
x = dec2bin(0:2^n-1, 8);
Or if you really want a loop:
n = 8;
x = repmat(' ', 2^n-1, 8); % Pre-allocate
for i = 0:2^n-1
x(i+1, :) = dec2bin(i,8);
end
x
[EDITED] If you want the numbers 0 and 1 instead of a char matrix with '0' and '1', either subtract '0':
x = dec2bin(0:2^n-1, 8) - '0';
But to avoid the conversion to a char and back again, you can write an easy function also:
function B = Dec2BinNumeric(D, N)
B = rem(floor(D(:) ./ pow2(N-1:-1:0)), 2);
end
PS. You see, the underlying maths is not complicated.