how to make a for loop for a binary number ?

11 vues (au cours des 30 derniers jours)
tomer polsky
tomer polsky le 4 Juil 2018
Modifié(e) : Guillaume le 4 Juil 2018
I want to build a program that converts from binary to decimal (I know that there is command for this , I want to build it my self ) so for exmple if
x=10010
I want to press x(3) and get 0 ( just like if i have an array of numbers for exmaple x=[1 42 13 ] so x(2)=42 ) how do i do it ?

Réponses (1)

Stephen23
Stephen23 le 4 Juil 2018
Modifié(e) : Stephen23 le 4 Juil 2018
In MATLAB binary numbers are normally stored as char vectors:
>> x = '10010'
x = 10010
>> x(3)
ans = 0
>> bin2dec(x)
ans = 18
You could put them as separate elements of a numeric array, but there is little advantage to this (and it makes displaying them harder). Note that the conversion from char vector to numeric vector (and back again) is trivial:
>> y = x-'0'
y =
1 0 0 1 0
>> char(y+'0')
ans = 10010
As an alternative you could write your own class (not trivial).
  1 commentaire
Guillaume
Guillaume le 4 Juil 2018
Modifié(e) : Guillaume le 4 Juil 2018
Storing the bits as 0/1 digits of a numeric array has the slight advantage that you can apply OR, XOR, AND and CMP operations (using |, xor, & and ~ respectively, not the bitxxx operators), as long as the bits are aligned of course.
Arithmetics (addition, subtraction, etc.) is still out with either model.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by