当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

The problem is that I'm trying to decrypt a char value retrieved by an Access DB.

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

I tried to use different encodings but I can't figure out where is the problem.

Any suggestion?

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.

SOLVED

The character '†' is in the Windows 1252 code page. So I get a byte[] with the correct encoding.

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.

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

Like in your case '†' can be 134 as you say and 8224 as Oded mentioned.

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

网友答案:

Your problem is that '†' is 8224, not 134. (@Oded mentioned this first) You can use '\u0086' instead, which is 134.

分享给朋友:
您可能感兴趣的文章:
随机阅读: