hello everbody hahzu contain

1 visualización (últimos 30 días)
Steven Thies
Steven Thies el 18 de Feb. de 2021
Comentada: Les Beckham el 20 de Feb. de 2021
f
  3 comentarios
Stephen23
Stephen23 el 19 de Feb. de 2021
Editada: Stephen23 el 19 de Feb. de 2021
Original question retrieved from Google Cache:
"Dual-Code in decimal number function?"
Hello people,
i want to convert a dual/binary Number to a decimal number. (Without using bin2dec, dec2bin or other)
Here is my function but when i try it, then the output is = NaN
Please help me.
function y = function_dual_decimal(x)
total = 0;
for i = 1 : length(x)
total = total + str2double(x(i)) * 2^(length(x) - i);
end
format long
y = total;
end
Les Beckham
Les Beckham el 20 de Feb. de 2021
Thank you @Stephen Cobeldick for restoring the original question. I still don't understand why people delete their questions when they get an answer.

Iniciar sesión para comentar.

Respuestas (1)

Les Beckham
Les Beckham el 19 de Feb. de 2021
Editada: Les Beckham el 19 de Feb. de 2021
Your code does what you want if you pass it a character array. For example if you pass '11', you get 3 as a result. Note the single quotes. They are necessary.
Interestingly, it does not work with the new string type using double quotes. Passing "11" results in 11 (yes, 11 as a double). Totally not expected and, in my mind, a bug.
edit: actually, the reason for this is that the length of "11" is one, while the length of '11' is two. So, this is expected
As you discovered, passing a number to this doesn't work. The function calls str2double which doesn't expect a number.
When you pass the number 11 you are essentially doing str2double(11) which returns NaN.
By the way, can you explain what you mean by a "dual/binary" number? I'm not acquainted with "dual" numbers. Perhaps that refers to base 2 (similar to how decimal refers to base 10)? Maybe I'll learn something new today. I like when I can do that.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by