MATLAB Answers

How to convert decimal into binary?

256 views (last 30 days)
Sky Scrapper
Sky Scrapper on 22 Jan 2019
Edited: AB WAHEED LONE on 6 Mar 2021
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?
  4 Comments
Stephen Cobeldick
Stephen Cobeldick on 22 Jan 2019
Get rid of the loop:
>> V = 0:pow2(8)-1;
>> dec2bin(V)
ans =
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001
00001010
... lots of rows here
11111010
11111011
11111100
11111101
11111110
11111111

Sign in to comment.

Accepted Answer

Jan
Jan on 22 Jan 2019
Edited: Jan on 22 Jan 2019
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.
  9 Comments
Jan
Jan on 23 Jan 2019
If
dec2bin(0:2^n-1, 8) - '0'
is working, calling
Dec2BinNumeric(0:2^n-1, 8)
is not a serious difference.

Sign in to comment.

More Answers (2)

PRAVEEN GUPTA
PRAVEEN GUPTA on 8 Jul 2019
i have string of number [240 25 32 32]
i want to convert them in binary
how can i do this???
  2 Comments
AB WAHEED LONE
AB WAHEED LONE on 6 Mar 2021
I know it is late but somwhow it may help
bin_array=dec2bin(array,8)-'0';

Sign in to comment.


vandana Ananthagiri
vandana Ananthagiri on 5 Feb 2020
function A = binary_numbers(n)
A = double(dec2bin(0:((2^n)-1),n))-48;
end
  1 Comment
Walter Roberson
Walter Roberson on 5 Feb 2020
Why 48?
I know the answer, but other people reading your code might not, so I would recommend either a comment or a different representation.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by