简体   繁体   English

在int和char之间转换错误并返回C#

[英]Wrong converting between int and char and back in C#

probably mine is a silly question, but I'm having troubles converting a char value into an int and convert back. 可能我的是一个愚蠢的问题,但我有麻烦将char值转换为int并转换回来。

The problem is that I'm trying to decrypt a char value retrieved by an Access DB. 问题是我正在尝试解密Access DB检索到的char值。

Here is my code 这是我的代码

char chrVal = 'M';
int intVal = (int)chrVal; // Output 77 'M'
// Now trying to encrypt using XOR
int encIntVal = intVal ^ 203; // Output 134 '†'
// Convert back
char correct = (char)(encIntVal ^ 203); // Output 'M' - CORRECT
char wrong = (char)('†' ^ 203); // Output WRONG value

The fact is that when I use the int resulting value from the encrypt XOR, I get correct result ('M'). 事实是,当我使用加密XOR的int结果值时,我得到正确的结果('M')。 Instead, when I use the char result from the encrypt XOR (that is what I have in the DB), I get wrong result (unreadable character). 相反,当我使用加密XOR的char结果(这就是我在DB中所拥有的)时,我得到了错误的结果(不可读的字符)。

I tried to use different encodings but I can't figure out where is the problem. 我试图使用不同的编码,但我无法弄清问题在哪里。

Any suggestion? 有什么建议吗?

UPDATE UPDATE

I found that probably the problem is with ADO.NET OleDbDataReader, because (int)Convert.ToChar(dr["Sex"]) gives me 8224 instead of 134, but I can't find a solution yet. 我发现可能问题出在ADO.NET OleDbDataReader上,因为(int)Convert.ToChar(dr [“Sex”])给了我8224而不是134,但我找不到解决方案了。

SOLVED 解决了

The character '†' is in the Windows 1252 code page. 字符“†”位于Windows 1252代码页中。 So I get a byte[] with the correct encoding. 所以我得到一个带有正确编码的byte []。

byte[] byteVal = Encoding.GetEncoding(1252).GetBytes(dr["Sex"])
char correct = (char)(byteVal[0] ^ 203); // Output 'M'

Thanks 谢谢

'†' character can be front character for not one but many Unicode values. '†'字符可以是前面的字符,不是一个而是许多Unicode值。

I can create a font where 'A' will not be just for 65 ASCII value but any value or i can create a font where all character are 'A'. 我可以创建一个字体,其中'A'不仅仅是65个ASCII值,而是任何值,或者我可以创建一个所有字符都是'A'的字体。

Like in your case '†' can be 134 as you say and 8224 as Oded mentioned. 就像你的情况一样,'†'可以是134,如你所说,8224就像Oded所提到的那样。

Give more emphasis on ASCII/Unicode values and not on what that value when converted to character looks like.

你的问题是'†'是8224,而不是134.(@Oded首先提到这个)你可以使用'\†'代替,这是134。

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

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