how to make a for loop for a binary number ?

조회 수: 10 (최근 30일)
tomer polsky
tomer polsky 2018년 7월 4일
편집: Guillaume 2018년 7월 4일
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