Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字符转换为大于256的整数_C#_Types - Fatal编程技术网

C#字符转换为大于256的整数

C#字符转换为大于256的整数,c#,types,C#,Types,我需要将一些字符转换为int值,但大于256。这是我将int转换为char的函数。我需要把它倒过来 public static string chr(int number) { return ((char)number).ToString(); } 此函数不起作用-它只返回0-256,ord(chr(i))==i public static int ord(string str) { return Encoding.Unicode.GetBytes(str)[0]; } 问题

我需要将一些字符转换为int值,但大于256。这是我将int转换为char的函数。我需要把它倒过来

public static string chr(int number)
{
    return ((char)number).ToString();
}
此函数不起作用-它只返回0-256,
ord(chr(i))==i

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

问题是,
ord
函数将字符串的字符截断为第一个字节,这是由UNICODE编码解释的。这句话

Encoding.Unicode.GetBytes(str)[0]
//                            ^^^
返回
字节
数组的初始元素,因此它必须保持在0..255范围内

您可以按如下方式修复
ord
方法:

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

既然您不太关心编码,直接在
chr()
函数中将
int
强制转换为
char
,那么为什么不试试另一种方法呢

    Console.WriteLine((int)'\x1033');
    Console.WriteLine((char)(int)("\x1033"[0]) == '\x1033');
    Console.WriteLine(((char)0x1033) == '\x1033');
字符在C中有2字节长(UTF-16编码)#


在MSDN上转换:

字符和字节在C#中是不同的。char和int之间的转换很简单:(char)intValue或(int)myString[x]。

可能使用不同的编码?什么编码?我尝试了utf-8和ascii,但它不起作用,我正在制作加密函数来制作bot,我正在从php转换它,我实际上需要php ord函数。
Encoding.Unicode.GetBytes
返回一个字节数组。一个字节是无符号的:也许我认为它错了,但如果只返回字节数组的第一个位置,该值将始终在0到255之间…
int I=(int)“ğ”将给出287<代码>字符c=(字符)287
是反向操作。为什么使用编码?一个简单的整数转换就足够了吗?@usr不,没有通用性。似乎OP希望使某种编码依赖于某些东西——也许他计划在一个单独的参数中将不同的编码传递给他的
Ord
。我猜不出他的意图,所以我尽可能多地保留了他的代码。@usr也许你们是对的,但我认为最好让新的行动有一点怀疑。
char c1; // TODO initialize me
int i = System.Convert.ToInt32(c1); // could be greater than 255
char c2 = System.Convert.ToChar(i); // c2 == c1