Two questions if I may.
1) I have an ascii string the represents the hex output of a string.
For instance:
"244750524d43". I need to convert this to the actual string "$GPRMC".
Is there a string utilitility for handling this kind of conversion or
do I just need to do it by shifts, subtracts, and ORs (and trial and
error)? I have misplaced my Schildt book and I remember he lists a
great variety of C string functions.
2) Could you recommend an online location that covers the cin members?
Thanx,
jh
Here's working example of such conversion:
--------------------------------------
int main()
{
const char* src = "244750524d43";
char dst[16] = { 0 };
char* p = dst;
while(*src)
{
char hi = *src - '0';
++src;
if(!*src) break;
char lo = *src - '0';
++src;
*p = (hi << 4) | lo;
++p;
}
return 0;
}
--------------------------------------
> 2) Could you recommend an online location that covers the
> cin members?
"cin"
http://msdn2.microsoft.com/en-us/library/71t65ya2(VS.80).aspx
Alex
I think you have the same bug I have. The code works fine for 0-9 but
the 'd' caused a problem and the output is "$GPRtC". Upper case will
be a problem too. Nonetheless your example is much cleaner than mine
so I will continue with yours, handling cases for a-f and A-F.
Thanks again,
jh
jh
int main()
{
const char* src = "4A4B4C232c244750524d43";
char dst[16] = { 0 };
char* p = dst;
while(*src)
{
char hi = *src - '0';
++src;
if(!*src) break;
char lo = *src;
cout << "lo" << lo;
while(1)
{
if(lo >= ' ' && lo <= '/')
{
lo -= ' ';
}
if(lo >= '0' && lo <= '9')
{
lo -= '0';
break;
}
if(lo >= 'a' && lo <= 'f')
{
lo -= 0x57;
break;
}
if(lo >= 'A' && lo <= 'F')
{
lo -= 0x37;
break;
}
}
++src;
*p = (hi << 4) | lo;
++p;
}
cout << dst << endl;
return 0;
}
Yes, you're right, of course. Here's correct version:
int xchtoi(int c)
{
c = toupper(c);
if(isxdigit(c))
{
if(isdigit(c))
return c - '0';
return c - 55;
}
return 0;
}
int main()
{
const char* src = "244750524d43";
char dst[16] = { 0 };
char* p = dst;
while(*src)
{
char hi = xchtoi(*src);
++src;
if(!*src) break;
char lo = xchtoi(*src);
Thanks,
jh
>
> if(isxdigit(c))
> {
> if(isdigit(c))
> return c - '0';
>
to here.
Thanks.
Hopefully by the time you reach that point, the compiler realizes that
having passed isxdigit and failed isdigit, c is a letter, and toupper then
optimizes to
c &= ~32;
If the compiler can't figure that out, help it along by using _toupper
instead.