Re: Convert native character string to ASCII array of integers



Tomás Ó hÉilidhe said:

<snip>

Please my MakeASCII function! Rip it apart!

Well, I won't rip it apart, but I think I can let a little air out of it.

#include <string.h>

void MakeASCII(unsigned char *pos,char const *pc)
{
const char *bcs =
" !\"#$%&'()*+,-./0123456789:;<=>?@"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"[\\]^_`"
"abcdefghijklmnopqrstuvwxyz"
"{|}~";
const char *cur = NULL;

while(*pc != '\0')
{
cur = strchr(bcs, *pc);
if(cur != NULL)
{
*pos++ = (cur - bcs) + 32;
}
else
{
*pos++ = *pc;
}
++pc;
}
*pos = '\0';
}

If you hit performance issues with that one, consider this alternative:

#include <string.h>
#include <limits.h>

void MakeASCII(unsigned char *pos,char const *pc)
{
const char *bcs =
" !\"#$%&'()*+,-./0123456789:;<=>?@"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"[\\]^_`"
"abcdefghijklmnopqrstuvwxyz"
"{|}~";
static char att[UCHAR_MAX + 1] = {0};

const char *cur = bcs;
int i = 0;

if(att[' '] != 32) /* do we need to set up the array? */
{
/* defaults */
for(i = 0; i < UCHAR_MAX + 1; i++)
{
att[i] = (char)i;
}

/* known ASCII characters */
i = 32;
while(*cur != '\0')
{
att[*cur++] = i++;
}
}

while(*pos++ = att[*pc++])
{
continue;
}
}


--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.



Relevant Pages

  • Re: Environment Variable - Parent Process --- TIA
    ... #define O0O void ... #define OO0 const ... #define OOO char ... OO0 const ...
    (comp.lang.c)
  • Re: Whats the deal with const?
    ... void print_first_5(char *x) ... printf(buf); ... void PrintFirst5 ... functions using const arguments, ...
    (comp.lang.c)
  • Re: dh, the daemon helper
    ... some type is a special case, while const ordinarily binds to the ... ie char const * is a pointer to a constant ... no point in returning memory to the malloc heap. ... 2004 is the UNIX standard. ...
    (comp.unix.programmer)
  • Re: dh, the daemon helper
    ... some type is a special case, while const ordinarily binds to the ... ie char const * is a pointer to a constant ... since this is the way UNIX(*) processes work. ...
    (comp.unix.programmer)
  • Re: Q about passing data as a const array
    ... The const on the len parameter is superfluous; ... exactly equivalent to "const char *data", ... void func(const struct mydata foo); ... Applying const to a pointer parameter can be quite useful, ...
    (comp.lang.c)