Alternative method to dec2bin function
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Haseeb Hashim
el 7 de Mzo. de 2022
I need help in the the code with alternative to bin2dec function which gives output in the double class
I have been trying but no success. Can anyone help
6 comentarios
Rik
el 7 de Mzo. de 2022
If you want to improve this code: try to determine the number of bits you need. That way you can use array operations. That removes the need for a loop and prevents dynamically growing your bin array.
Respuesta aceptada
Jan
el 7 de Mzo. de 2022
Editada: Jan
el 7 de Mzo. de 2022
Some simplifications:
% Replace:
flag = true;
while flag == true
% by
while true
If you have checked for:
if bin(i) == 0
an
else
is enough and there is no reason to check for
elseif bin(i) ~= 0
again. But in your case there is no need to distinguish the 2 cases, because num = floor(num/2) works in all cases. Instead of catching the last bin manually, you can do this in the loop also:
num = 29;
i = 1;
while true
bin(i) = rem(num, 2);
num = floor(num / 2);
if num == 0
break
end
i = i + 1;
end
flip(bin)
Or even simpler: Check the condition instead of breaking an infinite loop:
num = 29;
bin = [];
while num > 0
bin(end+1) = rem(num, 2);
num = floor(num / 2);
end
flip(bin)
The Matlabish way is to omit the loop and to determine the number of bits in advance:
nBit = floor(log2(num)) + 1;
bin = rem(floor(num .* pow2(1-nBit:0)), 2);
Take the time to understand, what's going on here. Run it in pieces:
1-nBit:0
pow2(1-nBit:0)
num .* pow2(1-nBit:0)
floor(num .* pow2(1-nBit:0))
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical 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!