Flea777
Flea777

Reputation: 1022

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

Upvotes: 3

Views: 1271

Answers (2)

Tim S.
Tim S.

Reputation: 56536

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

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

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

Upvotes: 3

Related Questions