简体   繁体   中英

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.

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

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