How do I take into account negatives when going from binary to integer. My function that I created is below

Viewed 54

**The problem is every time I run my function through examples in the command prompt some of them convert correctly while others don't, and I think it's be because the function is not taking into account the leading 0 or 1 for positive or negative. **

%The decode function should return x, the decoded base-10 integer of b.

    function [x] = decode(b)
    x=0;

  %Assign n to the length of b. Use the strlength function.

    n=strlength(b);
    temp_b=b;




  %Print the first output statement
  

    fprintf("Assume %s represents an integer encoded with %i-bit two's complement\n", b, n); 

  %Use variables, a loop, and if statements to implement 
  %an algorithm to compute x, the decoded base-10 integer of b.  
  %Do not use any built-in Matlab functions that converts a binary
  %number or bit string to an integer. 
  %Do not use the flip Matlab function.  

 

    decimalnum=0;
     for i=1:n
         temp1=str2num(b(i))*2^(length(b)-i);
         decimalnum=decimalnum+temp1;
         x=decimalnum;
     end
    ```
      %After computing x, call the print(b, x) function
    
        
        end

%Print the last line of output in this program
%in a consistent manner. This function is already
%implemented for you, and it should NOT be modified.
%b is assumed to be bit string of length n > 0, and 
%x is the decoded base-10 integer of b.

    function [] = print(b, x)
      n = strlength(b);
      fprintf("%s decoded as a base-10 integer is %i \n", b, x);
    end

0 Answers
Related