How to convert char to hex
I want to create a program where a user inputs some numbers and code is capable of adding those number by first converting them into hexadecimal character and then the addition procedure is executed. I know this sounds really awkward but I want to do this via programming. Is this possible? Can I convert char value to hex and then add them?
Re: How to convert char to hex
Code:
char *HexStringConversion (char *hStr)
{
char *str = new char[(strlen(hStr)*2)+1];
char *str1 = hStr;
char *str2 = str;
while('\0' != *str1)
{
sprintf(str2, "%02X", (char)(*str1++));
str2+=2;
}
*(str2) = '\0';
return(str);
}
You can call the above function to convert your characters or strings into hexadecimal number and then add them in your main as normally you would do.
Re: How to convert char to hex
There is no need of any functions if you are doing so in C language. All you need to do is except the number and then display it using "%x". You can even manipulate with this value if you want.
Code:
# include <stdio.h>
# include <conio.h>
int main()
{
clrscr();
char chr[15];
scanf ("%s", &chr);
printf ("%x\n", chr[0]);
getch();
return 0;
}
Re: How to convert char to hex
The C++ code goes as below:
Code:
# include <iostream.h>
static const char HexToAsciiValue[256][2] = { {'0','0'}, {'0','1'}, .... {'F','E'},{'F','F'} };
string CharToHex (const unsigned char* pArray, unsigned int strLen)
{
string str;
str.resize (strLen*2);
char* pszHex = &str[0];
const unsigned char* pEnd = pArray + strLen;
for (const unsigned char* pChar = pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = HexToAsciiValue[*pChar][0];
pszHex[1] = HexToAsciiValue[*pChar][1];
}
return str;
}