Encoding problem

  • Thread starter Mats-Lennart Hansson
  • Start date
M

Mats-Lennart Hansson

Hi,
I want to get the ANSI value (0-255) of a character. Assume I create a
character like this:

string s = new string((char) 151, 1);

Now I want to get the ANSI value (151) for this character. How do I do this?

When using ASCII I, of course get the wrong value:

byte[] arr = Encoding.ASCII.GetBytes(s); --> [63]

When using Unicode, I get two bytes where the first one is 151

byte[] arr = Encoding.Unicode.GetBytes(s); --> [151, 0]

Any help is appreciated!

Thanks,

Mats-Lennart
 
J

Jon Skeet [C# MVP]

Mats-Lennart Hansson said:
I want to get the ANSI value (0-255) of a character. Assume I create a
character like this:

string s = new string((char) 151, 1);

When you say "the ANSI value", which ANSI encoding are you talking
about?

The new string you've given above has the *Unicode* character 151 in
it.

I think you need to reconsider your problem with a bit more encoding
knowledge. See

http://www.pobox.com/~skeet/csharp/unicode.html

I suspect that Encoding.Default is going to be useful to you, but you
need to understand a few more things first. The above should help you.
 
M

Morten Wennevik

Hi Mats-Lennart,

ASCII is 7-bit, so 151 will be too high (not sure why it returns 63 and
not 23 as I would expect, maybe someone can clarify).

Unicode returns the 16-bit value of the caracter, the most significant
byte first, which in your case holds the 8-bit character.


Happy coding!
Morten Wennevik [C# MVP]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top