This is pretty much the same, but it's all I've got at the moment.
#include <stdio.h>
char *foo(char *dst, const char *src)
{
char *start = dst;
while ( *src )
{
dst += sprintf(dst, "%x", (unsigned)*src++);
}
return start;
}
char *bar(char *dst, const char *src)
{
char *start = dst;
while ( *src )
{
unsigned value;
if ( sscanf(src, "%2x", &value) == 1 )
{
src += 2;
*dst++ = value;
}
}
*dst = '\0';
return start;
}
int main(void)
{
const char abc[] = "ABC";
char over [ sizeof abc * 2 - 1 ], back [ sizeof abc ];
printf("\"%s\" -> \"%s\"\n", abc, foo(over, abc));
printf("\"%s\" -> \"%s\"\n", over, bar(back, over));
return 0;
}
/* my output
"ABC" -> "414243"
"414243" -> "ABC"
*/
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Perhaps discard the standard routines and roll your own.
#include <stdio.h>
#include <ctype.h>
unsigned char *foo(unsigned char *dst, const unsigned char *src)
{
static const unsigned char nibble[] =
{
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
unsigned char *start = dst;
while ( *src )
{
*dst++ = nibble [ *src >> 4 ];
*dst++ = nibble [ *src++ & 0xF ];
}
*dst = '\0';
return start;
}
unsigned char *bar(unsigned char *dst, const unsigned char *src)
{
unsigned char *start = dst;
while ( *src )
{
if ( isdigit(*src) )
{
*dst = *src++ - '0';
}
else
{
*dst = *src++ - 'A' + 10;
}
*dst <<= 4;
if ( isdigit(*src) )
{
*dst++ += *src++ - '0';
}
else
{
*dst++ += *src++ - 'A' + 10;
}
}
*dst = '\0';
return start;
}
int main(void)
{
const unsigned char abc[] = "ABCMNO";
unsigned char over [ sizeof abc * 2 - 1 ], back [ sizeof abc ];
printf("\"%s\" -> \"%s\"\n", abc, foo(over, abc));
printf("\"%s\" -> \"%s\"\n", over, bar(back, over));
return 0;
}
/* my output
"ABCMNO" -> "4142434D4E4F"
"4142434D4E4F" -> "ABCMNO"
*/
This is for ASCII, and I think it is right. But I was wrong with it a minute ago.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
I performed a dry run. I think it would be better to use
if (*src <= '9')
rather than
if (isdigit(*src))
What do you think...
Sutanu
If that works better, go ahead. Many times the standard functions are implemented faster than writing an equivalent, but not always.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
if( *src <= '9' )
what if *src < '0' ? isdigit() will catch that, but your if statement won't.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343