TechArena Community How to convert char to hex

#1
26-08-2009
 Member Join Date: Jun 2009 Posts: 87
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?
#2
26-08-2009
 Member Join Date: May 2008 Posts: 2,383
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.
__________________
The FIFA Manager 2009 PC Game
#3
26-08-2009
 Member Join Date: Nov 2008 Posts: 996
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;
}```
#4
26-08-2009
 Member Join Date: Feb 2008 Posts: 1,848
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;
}```

 Tags: