0

How do I convert from unicode to single byte in C#?

This does not work:

int level =1;
string argument;
// and then argument is assigned

if (argument[2] == Convert.ToChar(level))
{
    // does not work
}

And this:

char test1 = argument[2];
char test2 = Convert.ToChar(level);

produces funky results. test1 can be: 49 '1' while test2 will be 1 ''

Michael Myers
  • 184,092
  • 45
  • 284
  • 291
xarzu
  • 8,127
  • 38
  • 103
  • 146
  • http://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent – Robert Harvey Apr 12 '10 at 20:21
  • 1
    Do you want `level` to be converted to the char '1' , or a char with value 1 ? That's the same difference as in doing `char c = '1'` and `char c = 1` – leeeroy Apr 12 '10 at 20:23

4 Answers4

3

How do I convert from unicode to single byte in C#?

This question makes no sense, and the sample code just makes things worse.

Unicode is a mapping from characters to code points. The code points are numbered from 0x0 to 0x10FFFF, which is far more values than can be stored in a single byte.

And the sample code has an int, a string, and a char. There are no bytes anywhere.

What are you really trying to do?

Jeffrey L Whitledge
  • 55,844
  • 9
  • 67
  • 97
2

Use UnicodeEncoding.GetBytes().

UnicodeEncoding unicode = new UnicodeEncoding();
Byte[] encodedBytes = unicode.GetBytes(unicodeString);
David
  • 6,851
  • 1
  • 40
  • 38
1

char and string are always Unicode in .NET. You can't do it the way you're trying.

In fact, what are you trying to accomplish?

John Saunders
  • 159,224
  • 26
  • 237
  • 393
1

If you want to test whether the int level matches the char argument[2] then use

  if (argument[2] == Convert.ToChar(level + (int)'0'))
Henk Holterman
  • 250,905
  • 30
  • 306
  • 490