In: Computer Science
A byte is made up of 8 bits although a byte is rarely represented as a string of binary digits or bits. Instead, it is typically presented as a pair of hexadecimal digits where each digit represents 4 bits or half a byte or "nibble." We have been reading in hex digits and outputting their decimal value, but what we really want to do is create a byte from a pair of hex digits read from input.
Create a C program that:
The printf() function supports outputting an integer as a hexadecimal number using the %x (where the hexadecimal letters are presented in lower-case) and %X (where the hexadecimal letters are presented in upper-case).
To pack two integers that have values represented with only 4 bits, you need to perform two operations with the integers:
After the shift and the OR, the first integer will not have the lower 8 bits (byte) set to the values represented by the two characters read from input.
// C program to convert a pair of hexadecimal characters to BYTE
#include <stdio.h>
#include <string.h>
int main()
{
char hexa[2], byte[8] = "";
int i,n=0,l;
/* Enter a pair of hexadecimal digts from user */
printf("Enter a pair of hexadecimal digits: ");
x:gets(hexa);
l=strlen(hexa);
if (l>2)
{printf(" Please enter only two hexadecimal digits");
goto x;
}
/*loop to extract digit and find binary of each hex digit */
for(i=0; hexa[i]!='\0'; i++)
{
switch(hexa[i])
{
case '0':
strcat(byte, "0000");
break;
case '1':
strcat(byte, "0001");
break;
case '2':
strcat(byte, "0010");
break;
case '3':
strcat(byte, "0011");
break;
case '4':
strcat(byte, "0100");
break;
case '5':
strcat(byte, "0101");
break;
case '6':
strcat(byte, "0110");
break;
case '7':
strcat(byte, "0111");
break;
case '8':
strcat(byte, "1000");
break;
case '9':
strcat(byte, "1001");
break;
case 'a':
case 'A':
strcat(byte, "1010");
break;
case 'b':
case 'B':
strcat(byte, "1011");
break;
case 'c':
case 'C':
strcat(byte, "1100");
break;
case 'd':
case 'D':
strcat(byte, "1101");
break;
case 'e':
case 'E':
strcat(byte, "1110");
break;
case 'f':
case 'F':
strcat(byte, "1111");
break;
default:
n=1;
}
}
if(n==0)
{
printf("Hexademial Pair = %s\n", hexa);
printf("Byte Conversion = %s", byte);
}
else
printf("Wrong hexadecimal input");
return 0;
}