String Conversion question

  • Thread starter Thread starter KA Kueh
  • Start date Start date
K

KA Kueh

Dear all,

I have a requirement to replace the ' character with ASCII character (146)
in C# but it seems that when I do the following the conversion is lost.

char t = Convert.ToChar(146);
string s = t.ToString();

The trouble now is that the s object now contains the ASCII character (63)
now. I know because when I store the string to SQL database it show the
ASCII charactor (63). Can someone help? Thanks.

Regards,
Kueh.
 
Char is Unicode...

If you're referencing 8 bit characters ( i.e ASCII ), the use the Byte
object instead.

byte t = Convert.ToByte ( 146 );

Hopefully this works as expected!
Daniel.
 
Hi Kueh,

There is no ASCII character 146. Characters in the range 128-255 belong to extended ASCII and vary depending on code page used.

char[] c = Encoding.GetEncoding(1252).GetChars(new byte[]{146});

c[0] = ’

c[0] is now the Unicode representation of character 146 in code page 1252
 
Or you could simply use

byte t = 146;

When initializing and declaring at the same time, you can use an integer value to create a byte.
 
KA Kueh said:
I have a requirement to replace the ' character with ASCII character (146)
in C# but it seems that when I do the following the conversion is lost.

There is no such thing as ASCII 146.

See http://www.pobox.com/~skeet/csharp/unicode.html
char t = Convert.ToChar(146);
string s = t.ToString();

The trouble now is that the s object now contains the ASCII character (63)
now. I know because when I store the string to SQL database it show the
ASCII charactor (63). Can someone help? Thanks.

You don't know any such thing. The string contains Unicode 146, which
is "Private Use 2" - not what you meant, I suspect.

The reason you see '?' in the database is that whever encoding is being
used doesn't have that character in it, so '?' is being used instead.
 
Dear Morten,

Thanks for the sample code. Only your sample works. Is this the only way
to return extended ASCII characters? Thanks again.

Regards,
Kueh.


Morten Wennevik said:
Hi Kueh,

There is no ASCII character 146. Characters in the range 128-255 belong
to extended ASCII and vary depending on code page used.
char[] c = Encoding.GetEncoding(1252).GetChars(new byte[]{146});

c[0] = '

c[0] is now the Unicode representation of character 146 in code page 1252
 
It's the only way I could think of. Strings use Chars, and Char is unicode. This won't matter if the text is regular ASCII only (char 0-127) since the unicode is the same for those characters, but once you move into extended ASCII, the only way I can think of handling those characters are in byte arrays.
 
Back
Top