简体   繁体   中英

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

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 ''

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 byte s anywhere.

What are you really trying to do?

Use UnicodeEncoding.GetBytes() .

UnicodeEncoding unicode = new UnicodeEncoding();
Byte[] encodedBytes = unicode.GetBytes(unicodeString);

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?

如果要测试int 级别是否与char 参数[2]相匹配,请使用

  if (argument[2] == Convert.ToChar(level + (int)'0'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM