Write function to convert decimal to binary

I am struggling to solve the following question: Write a function `dec_to_bin` that takes a decimal number as input and returns its binary representation as a string. Avoid using the built-in function `dec2bin`. Ensure that the function handles non-integer inputs and outputs the binary representation accurately.

댓글 수: 4

DGM
DGM 2023년 11월 26일
What's the intended behavior when given non-integer inputs? I have to ask, since dec2bin() truncates the non-integer component.
You know there are lots of threads and FEX submissions already around. There are links over here ->
And you can use the search to find others.
There are three major competing representations for binary integers. There are a large number of competing representations for binary numbers that are not integers.
So how can I write the function for this question? Because I am new to this
Let us start with something simple. If the input is 5.1, then what is "its binary representation as a string" ? You can work it out by hand and show us the major intermediate steps

댓글을 달려면 로그인하십시오.

답변 (1개)

DGM
DGM 2023년 12월 5일
편집: DGM 2023년 12월 5일
Meh. I'm going to ignore negative numbers for now. The question doesn't seem to actually mention it, though I strongly suspect otherwise.
Since the question isn't answerable without somebody actually stating the requirements, here is a rudimentary fixed-point representation for positive numbers only. Does that meet the requirements? Nobody knows.
N = [6.375 14.5625];
bits = [4 4]; % bits dedicated to [whole fractional] parts
positivefixedpt(N,bits)
ans = 2×8 char array
'01100110' '11101001'
function out = positivefixedpt(in,bits)
% only operates on the magnitude of the input
% sign is ignored
N = abs(in(:)); % vectorize, get magnitude
p = (bits(1)-1):-1:(-bits(2)); % powers corresponding to given bits
out = floor(N./2.^p); % divide
out = char(mod(out,2) + 48); % mod, convert to char
end
Are there edge cases which can break this? Now it's your turn to guess.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2023년 11월 26일

편집:

DGM
2023년 12월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by