how to make a for loop for a binary number ?

11 次查看(过去 30 天)
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 ?

回答(1 个)

Stephen23
Stephen23 2018-7-4
编辑:Stephen23 2018-7-4
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 个评论
Guillaume
Guillaume 2018-7-4
编辑:Guillaume 2018-7-4
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by