简体   繁体   中英

C# char into int bigger than 256

i need to convert some char to int value but bigger than 256. This is my function to convert int to char. I need reverse it

public static string chr(int number)
{
    return ((char)number).ToString();
}

This function doesnt work - its returning only 0-256, ord(chr(i))==i

public static int ord(string str)
{
    return Encoding.Unicode.GetBytes(str)[0];
}

The problem is that your ord function truncates the character of the string to the first byte, as interpreted by UNICODE encoding. This expression

Encoding.Unicode.GetBytes(str)[0]
//                            ^^^

returns the initial element of a byte array, so it is bound to stay within the 0..255 range.

You can fix your ord method as follows:

public static int Ord(string str) {
    var bytes = Encoding.Unicode.GetBytes(str);
    return BitConverter.ToChar(bytes, 0);
}

Demo

Since you don't care much about encodings and you directly cast an int to a char in your chr() function, then why dont you simply try the other way around?

    Console.WriteLine((int)'\x1033');
    Console.WriteLine((char)(int)("\x1033"[0]) == '\x1033');
    Console.WriteLine(((char)0x1033) == '\x1033');

char is 2 bytes long (UTF-16 encoding) in C#

char c1; // TODO initialize me
int i = System.Convert.ToInt32(c1); // could be greater than 255
char c2 = System.Convert.ToChar(i); // c2 == c1

System.Convert on MSDN : https://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx

Characters and bytes are not the same thing in C#. The conversion between char and int is a simple one: (char)intValue or (int)myString[x].

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