简体   繁体   English

C#char into int大于256

[英]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. 我需要将一些char转换为int值但大于256.这是我将int转换为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 这个函数不起作用 - 它只返回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. 问题是你的ord函数将字符串的字符截断为第一个字节,由UNICODE编码解释。 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. 返回byte数组的初始元素,因此它必须保持在0..255范围内。

You can fix your ord method as follows: 您可以按如下方式修复您的ord方法:

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? 因为你不太关心编码而且你直接在你的chr()函数中将一个int为一个char ,那么为什么你不能简单地尝试另一种方法呢?

    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在C#中长度为2个字节(UTF-16编码)

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 MSDN上的System.Convert: https//msdn.microsoft.com/en-us/library/system.convert(v = vs.110).aspx

Characters and bytes are not the same thing in C#. 字符和字节在C#中不是一回事。 The conversion between char and int is a simple one: (char)intValue or (int)myString[x]. char和int之间的转换很简单:(char)intValue或(int)myString [x]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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