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

[C language] Integer to Hex String and Hex String to Integer(Follow the instruct

ID: 3755005 • Letter: #

Question

[C language] Integer to Hex String and Hex String to Integer(Follow the instruction and Only IN C)

1 Interger to Hex String Write the C function itox() to covert an integer to a hex string. Its prototype is described in the header file xbits.h. Write your code in the file xbits.c in your hw3 directory. You can build from the stub xbits.c from my hw3 directorv. The idea behind the itox function is to convert an int variable (int is 32 bits on our machine) ignment, we will consider directly to an ASCII string of hex numbers, '0', '1', ..., ' only positive integers. 'F'. In this ass The algorithm is as follows. 1. Divide the int by 16. 2. The remainder is the first hex digit, to be placed in hexstring [7]. Use , to represent remainder : 0, ,1, for remainder remainder = 11, and so on. 1, 'A, for remainder 10, 'B' for 3. Update the int to be the quotient. 4. Repeat steps 1, 2, and 3 for sizeof (int) * 2 times When Step 2 is executed for the second time, the hex digit will go into hexstring[6]; when Step 2 is executed for the third time, the hex digit will go into hexstring[5], and so on. 5. Terminate the hexstring with '10'. Note that the array hexstring declared by the caller can be declared with a size sizeof (int) * 2 + 1. sizeof ) is evaluated at compile time to be the number of bytes in a variable of a given type. For example, it is 4 bytes to an int on our machine, but it might be 8 bytes on a different machine. Thus sizeof ) allows your code to be portable.

Explanation / Answer

//C program

#include<stdio.h>

#include<string.h>

void itox(char hexstring[] ,int n){

int i=7,num;

while(i>=0){

num=n%16;

if(num>=0&&num<=9)hexstring[i]=(char)'0'+num;

else hexstring[i]=(char)'A'+num%10;

n/=16;

i--;

}

}

int xtoi(char hexstring[]){

int num=0,i;

for( i=0;i<8;i++){

num*=16;

char ch =hexstring[i];

if(ch>='0'&&ch<='9')

num+=ch-'0';

else num+=ch-'A'+10;

}

return num;

}

int main(){

char hexstring[8];

int n,i;

printf("Enter n : ");

scanf("%d",&n);

printf("%d in hex : 0x",n);

itox(hexstring,n);

for(i=0;i<8;i++)

printf("%c",hexstring[i]);

printf(" ");

printf("%d",xtoi(hexstring));

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote