Write a C program to convert a string to hexadecimal values.
#include <string.h>
void decimalToHexa(int data) {
int rem[10], count = 0;
char hexa[] = {'A', 'B', 'C', 'D', 'E', 'F'};
/* convert decimal to hexadecimal value */
while (data > 0) {
rem[count++] = data % 16;
data = data / 16;
}
while (count > 0) {
count--;
if (rem[count] > 9) {
printf("%c", hexa[rem[count] - 10]);
} else {
printf("%d", rem[count]);
}
}
printf("\n");
return;
}
int main () {
int i = 0;
char str[100];
printf("Enter your input string:");
fgets(str, 100, stdin);
str[strlen(str) - 1] ='\0';
while (str[i] != 0) {
printf("%c -> 0x", str[i]);
decimalToHexa(str[i]);
i++;
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:HelloWorld
H -> 0x48
e -> 0x65
l -> 0x6C
l -> 0x6C
o -> 0x6F
W -> 0x57
o -> 0x6F
r -> 0x72
l -> 0x6C
d -> 0x64
Enter your input string:HelloWorld
H -> 0x48
e -> 0x65
l -> 0x6C
l -> 0x6C
o -> 0x6F
W -> 0x57
o -> 0x6F
r -> 0x72
l -> 0x6C
d -> 0x64
No comments:
Post a Comment