In: Computer Science
Write the main.c program for a PSoC project that takes an input byte and converts it to an integer value in base 10 for subsequent processing within the program as an integer. (Example, 0x5A = 9010).
0x5A hexadecimal equals to 90 in base 10.
conversion tales place: 5 * 16 ^ 1 + A * 16 ^ 0
where A is equals to 10.
First way: Using inbuilt C Feature.
This is a very simple task. C programming language provides inbuilt functionality of converting numbers to another form.
First task is to declare a variable which can hold hexadecimal value like 0x5A. Integer data type is capable of storing the hexadecimal value. So a variable can be declared as follows:
int hexInput;
Next task is to get get the input in hexadecimal format. scanf function with format specifier %x can be used to scan hexadecimal value.
scanf("%X", &hexInput);
Last task is to get the decimal value that is base 10 value. Simply you can assign the hexInput to another integer type variable or use hexInput directly. To print the hexInput in base10 use the %d format specifier with printf statement.
base10Value = hexInput;
printf("Integer value: %d", base10Value);
where base10Value is an integer type variable.
Output:
Second way: Input in string form and converting to base 10
Take input in character array. Parse the input character by character. The input must start with 0x.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char hexInput[25], ch;
int base10Value = 0, length, i = 0;
// get the input from user
printf("Enter the hexadecimal value. Format should be 0x5A:
");
gets(hexInput);
// get the length of the input
length = strlen(hexInput);
// ignore first 2 characters. so loop till length is greater than
2.
while(length > 2)
{
// get the character begining from last
ch = hexInput[length - 1];
//decrement the length by 1
length--;
// if charcter is between 'A' and 'F' or 'a' and 'f', get the
decimal value and add 10
// add 10 is required as (ch - 'A') will give differnce in ASCII
value
if(ch >= 'A' && ch <= "F")
{
// i is used for power. as we are starting from last, i is
initialized to 0
base10Value += pow(16, i) * (ch - 'A' + 10);
printf("\n%d", base10Value);
}
else if(ch >= 'a' && ch <= "f")
{
base10Value += pow(16, i) * (ch - 'a' + 10);
printf("\n%d", base10Value);
}
// if ch is digit, subtract '0' from ch to get decimal value
else if(ch >= '0' && ch <= '9')
{
base10Value += pow(16, i) * (ch - '0');
printf("\n%d", base10Value);
}
// increment power value
i++;
}
printf("Integer value: %d", base10Value);
return 0;
}
Output: