I have a string which is 40FA
. I would like to perform an XOR operation to it and return a byte which is 0xBA
in this case. However, I'm only able to get that BA
in string. When I convert BA
to byte, I'm getting 186
.
string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);
int test = uid_1 ^ uid_2 ;
string final = test.ToString("X");
byte byteresult = Byte.Parse(final , NumberStyles.HexNumber);
I think there is a little misunderstanding here. You actually already solved your problem. The computer does not care whether the number is decimal or hexadecimal or octadecimal or binary. These are just representations of a number. So only you care how it is to be displayed.
As DmitryBychenko already said: 0xBA is the same number as 186. It won't matter for your byte array if you want to store it there. It only matters for you as a user if you want to display it.
EDIT: you can test it by running this line of code:
Console.WriteLine((byteresult == Convert.ToInt32("BA", 16)).ToString());
Your code actually does what you want if I understood you correctly from your comments.
string tmp = "40FA";
int uid_1 = Convert.ToInt32(tmp.Substring(0, 2), 16);
int uid_2 = Convert.ToInt32(tmp.Substring(2, 2), 16);
int test = uid_1 ^ uid_2 ;
string final = test.ToString("X");
// here you actually have achieved what you wanted.
byte byteresult = Byte.Parse(final , NumberStyles.HexNumber);
now you can use byteresult
to store it in a byte[]
, and this:
byte[] MyByteArray = new byte[4];
MyByteArray [0] = byteresult;
should execute without problems.