how to make a for loop for a binary number ?
12 views (last 30 days)
Show older comments
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 ?
0 Comments
Answers (1)
Stephen23
on 4 Jul 2018
Edited: Stephen23
on 4 Jul 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 Comment
Guillaume
on 4 Jul 2018
Edited: Guillaume
on 4 Jul 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.
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!