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

The value it is converting is a decimal value saved as Z. I need this to properl

ID: 3568867 • Letter: T

Question

The value it is converting is a decimal value saved as Z. I need this to properly print out my hex value. When I run it its giving me the wrong value. The hex value wanted should approximatly be 6-8 hex digits. Thanks for the help!

#include
#include
#include
#include

int cheggtest2(int x,int y,char hex[]){
int n,r,a,b,z;
z=0;
r=0;
r=15;
for(n=0;n<8;n++){
a=x&r;
b=y&r;
r=r*16;
if(a>b){
z=b+z;  
}
else{
z=a+z;
}  
}
   return z;
}

int cheggtest(int x,int y,char hex[]){
int n,r,q,b,z,d;
z=0;
r=0;
r=15;
for(n=0;n<8;n++){
q=x&r;
b=y&r;
r=r*16;
if(q>b){
z=b+z;  
}
else{
z=q+z;
}  
}
   int c=0,a[100],i=0;
z=d;
while (z>0)
{
a[i]=z%16;
z=z/16;
i++;
c++;
}
a[i]=b;
printf("Its hexadecimal equivalent is ");
for (i=c;i>=0;--i)
{
if (a[i]==10)
   printf("A");
else if (a[i]==11)
   printf("B");
else if (a[i]==12)
   printf("C");
else if (a[i]==13)
   printf("D");
else if (a[i]==14)
   printf("E");
else if (a[i]==15)
   printf("F");
else
   printf("%d",a[i]);
}
  

   return a[i];
}


int main()
{
   int x,y,z;
   char hex[100];
   printf("Enter Decimal Value 1: ");
   scanf("%d",&x);
   printf(" Enter Decimal Value 2: ");
   scanf("%d",&y);
   printf("%d ",cheggtest(x,y,hex));
   printf("%d ",cheggtest2(x,y,hex));
  
  
}

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <string.h>

void decimal_hex(int n, char hex[]) /* Function to convert decimal to hexadecimal. */
{
int i=0,rem;
while (n!=0)
{
rem=n%16;
switch(rem)
{
case 10:
hex[i]='A';
break;
case 11:
hex[i]='B';
break;
case 12:
hex[i]='C';
break;
case 13:
hex[i]='D';
break;
case 14:
hex[i]='E';
break;
case 15:
hex[i]='F';
break;
default:
hex[i]=rem+'0';
break;
}
++i;
n/=16;
}
hex[i]='';
  
int len=len=strlen(hex)-1;
for(i=0;i<strlen(hex)/2;i++)
{
hex[i]+=hex[len];
hex[len]=hex[i]-hex[len];
hex[i]=hex[i]-hex[len--];
}
}

int cheggtest2(int x, int y, char hex[]) {
int n, r, a, b, z;
z = 0;
r = 0;
r = 15;
for (n = 0; n < 8; n++) {
a = x&r;
b = y&r;
r = r * 16;
if (a > b) {
z = b + z;
} else {
z = a + z;
}
}
return z;
}

void cheggtest(int x, int y, char hex[]) {
int n, r, q, b, z, d;
z = 0;
r = 0;
r = 15;
for (n = 0; n < 8; n++) {
q = x&r;
b = y&r;
r = r * 16;
if (q > b) {
z = b + z;
} else {
z = q + z;
}
}
  
  
printf(" Its hexadecimal equivalent is ");
  
decimal_hex(z, hex);
printf("%s ",hex);


return;
}

int main() {
int x, y, z;
char hex[100];
printf("Enter Decimal Value 1: ");
scanf("%d", &x);
printf(" Enter Decimal Value 2: ");
scanf("%d", &y);
  
  
  
cheggtest(x,y,hex);
  


}

--------------------------------------------------------

OUTPUT

Enter Decimal Value 1: 1456745698

Enter Decimal Value 2: 2013344656

Its hexadecimal equivalent is 56012390