Tuesday 16 October 2018

Octave code for decimal to binary conversion

function result=decimal2binary(dividend)
i=1;
j=1;
 if dividend==0
    binary_value=0
  else
q_temp=dividend;
  while (q_temp>1)
  r_temp=mod(q_temp,2);
  binary_matrix(i,1)=q_temp;
  binary_matrix(i,2)=r_temp;
  display(binary_matrix);
  q_temp=floor(dividend/2);
  dividend=q_temp;
  i=i+1;
  end
  binary_matrix(i,2)=1;
  a=binary_matrix(:,2);
  b=a';
result=flip(b)
  end

end

This code is based on simple decimal to binary conversion .

Our number gets divide by 2. We get the result in two forms Quotient and Remainder. Remainder become the LSB and Quotient becomes dividend and again get divided by 2. Until Quotient become l. This condition is given in a while loop:

To store the values of Quotients and Remainders, I created a matrix binary_matrix with i rows and 2 columns. First column contains Quotient and Second column contains Remainder.

In this way we got all the bits. But I require column 2 only. So I extracted it. This will result into a matrix of (i*1) i rows and 1 column. I taken the transpose of it. Then arranged it in reverse order to get the result.  

Flaws of above program:
  1.  As this program contain loop it will be time consuming.
  2. This program will not convert float values to binary.


No comments:

Post a Comment

Program to solve 4 variable equation(octave code)

function [x,y,z,alpha]=eq4variable( aaaa1,bbbb1,dddd1,eeee1,cccc1,aaaa2,bbbb2,dddd2,eeee2,cccc2,aaaa3,bbbb3,dddd3,eeee3,cccc3,aaaa4,bbbb4,d...