Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(In C++)I need help implementing the following functions: int binary_to_decimal_

ID: 3882174 • Letter: #

Question

(In C++)I need help implementing the following functions:

int binary_to_decimal_signed(string b);

// precondition: b is a string that consists of only 0s and 1s

// postcondition: the decimal integer that is represented by b

string decimal_to_binary_signed(int n);

// precondition: n is an integer

// postcondition: n’s binary representation is returned as a string of 0s and 1s

string add_binaries_signed(string b1, string b2);

// precondition: b1 and b2 are strings that consists of 0s and 1s, i.e. b1 and b2 are binary

//                          two’s complement representations of two integers

// postcondition: the sum of b1 and b2 is returned. For instance, if b1 = “11”, b2 = “01”, // then the return value is “100”

string signed_extension(string b);

             // precondition: s is a string that consists of only 0s and 1s that is at most 16 bits

// postcondition: a 16 bit string has been returned as signed extension of s. For instane,

// if s = "0101" then return value will be "00000000000000000101" total 12

            // 0s are added in front of s

string twos_complement(string s);

            // precondition: s is a string that consists of only 0s and 1s

// postcondition: two's complement of s is returned as an 16 bits binary integer. For

//                       instance, if s = "1101", then return value will be "1111111111111101"

Explanation / Answer

string decimal_to_binary_signed(int n)
{
string s;
for(i=0; n>0; i++)
{
s[i]=n%2;
n= n/2;
}

return s;

}

int binary_to_decimal_signed(string b)

{
string s = b;
int val= 0;


int b= 1; //base

int l= b.length();
for (int i=l-1; i>=0; i--)
{
if (s[i] == '0')
{
val+= 0*b;
b = b * 2;
}
else
{
val += 1*b;
b = b * 2;
}
}

return val;
}

string add_binaries_signed(string b1, string b2)
{
int a=binary to desimal signed(b1);
int a=binary to desimal signed(b1);
int sum=a+b;
string s=desimal to binary signed(sum);
return s;
}


string signed_extension(string b)
{
string s;
int j=15;
for(int i=b.size();i>=0;i--)
{
s[j]=b[i];
j--;
}
for(int i=j;i>=0;i--)
{
s[i]='0';
}
return s;
  
}

string twos_complement(string s);
{
string res;
int len=s.size();
res=signed_extension(s);// converting into 16 bit
int i;
for(i=15;i>=0;i--)
{
if(res[i]=='1')
break;
}
for(int j=i;j>=0;j--)
{
if(res[j]=='1')
res[j]='0';
else
res[j]='1';
}
return res;
}