Helpful Information
 
 
Category: C Programming
Convert CString to ASCII values

In VC++ 6, I need to convert each character in a CString to their ASCII values. What function(s) should I use?

Any help is appreciated. Thanks.

Sounds like you're compiling with support for UNICODE strings. In that case, you use wctomb().

First of all, thanks for the quick response, Jon.

Actually I'm not doing anything related to UNICODE. The purpose of my function is to convert every single character in a CString to its ASCII value.

For example:
"abc.com" -> 97 98 99 46 99 111 109

I need the numerical ASCII values, so I dun think wctomb would work in my case. Do you have any other suggestions? Thanks.

Hmm...

Well, I suppose you can get the buffer (CString::GetBuffer()) and then assign the characters to an int. A char is really an int (short), so the types are interchangeable.

Ex:

char mychar = 'a';

printf("char: %c\n", mychar); // Prints the character 'a'
printf("ASCII: %d\n", mychar); // Prints the number 97

That's the only way I can think of to do get the ASCII value.

Thanks again.

I want to convert characters in name to ASCII, then append this to name2.

eg. name = "abc", name2="test";
then after the operation, i need "test878889".


Here is what I've got so far

CString name, name2;
char *ptr;
int length = name.GetLength();
int i;

ptr = name.GetBufferSetLength(length);

for (i=0; i<length; i++, ptr++)
{
name += (short)(*ptr);
}


but of course it's not turning out right. I get "testabc" instead of what i needed. what do you do to (*ptr) to get it's numerical value? Thanks a lot for your help!

Just adding...

you can easily assign the ascii value to an integer variable....

int i;
char c='A';

i=c; // i is now 65.

Ok the problem is that I'm not converting interger to CString correctly. I used _itoa() and it worked.

Thanks for all your help.:)

#include <stdio.h>

int main(int ac,char*av[]) {
char*pc;
while (NULL != *++av) {
for (pc = *av; *pc; ++pc)
printf("%4d",*pc);
putchar('\n');
}
return puts("Another fine work by Dave Lambert"), 0;
}


#if 0

-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sun Aug 28 18:56:15

make -k c && ./c this quick nutcase.
cc c.c -o c
116 104 105 115
113 117 105 99 107
110 117 116 99 97 115 101 46
Another fine work by Dave Lambert

Compilation finished at Sun Aug 28 18:56:15

#endif










privacy (GDPR)