Click here to Skip to main content
15,891,184 members

Converting chars to ASCII in C#

Nick Fisher (Consultant) asked:

Open original thread
Hi guys,

I'm converting an old VB application into C#, and part of the system requires me to convert certain special characters to their ASCII equivalent.

In VB, the code is:

XML
sValue = Asc("œ")  'which gives 156

sValue = Asc("°")  'which gives 176

sValue = Asc("£")  'which gives 163


These are the correct values according to http://www.ascii-code.com/.


But when doing the same conversion in C#, the first of these values gives a strange answer.

Here is the code:

C#
As ints:

int i1 = (int)Convert.ToChar("œ");    // which gives 339

int i2 = (int)Convert.ToChar("°");    // which gives 176

int i3 = (int)Convert.ToChar("£");    // which gives 163


As bytes:

byte i1 = (byte)Convert.ToChar("œ");    // which gives 83

byte i2 = (byte)Convert.ToChar("°");    // which gives 176

byte i3 = (byte)Convert.ToChar("£");    // which gives 163


What gives?! :( I'm suspecting it's something to do with the sign bit, but I can't see what.

Many thanks
Tags: C#, Visual Basic

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900