Reputation: 167
I have a string array
Receivedbyte[0]=5A
Receivedbyte[1]=3A
Receivedbyte[2]=7A
Receivedbyte[3]=60
I want to treat them as hex numbers and xor each of the value by 0x20. so I want my data to be 0x5A ^0x20 in the 0th location. and so on.
I Tried the following , but an error comes which says, input string is not in correct format.
static public string[] escapeFix(string[] Receivedbyte)
{
uint temp = Convert.ToUInt32(Receivedbyte[1]);
temp = temp ^ 0x20;
Receivedbyte[0] = Convert.ToString(temp);
Receivedbyte[1] = Receivedbyte[2];
Receivedbyte[2] = Receivedbyte[3];
return Receivedbyte;
}
Upvotes: 0
Views: 52
Reputation: 13069
You'll need to parse the string as hexadecimal values first, then XOR before converting back to strings.
void Main()
{
var receivedBytes = new string[] { "5A", "3A", "7A", "60" };
escapeFix(receivedBytes);
}
public static string[] escapeFix(string[] bytes)
{
return bytes
.Select(b => Convert.ToByte(b, 16) ^ 0x20)
.Select(b => b.ToString("X"))
.ToArray();
}
Upvotes: 0
Reputation: 1199
Convert.ToUInt32
tries to parse decimal string, but your input is hex, hence the error. Try byte.Parse(ReceivedBytes[1], NumberStyles.AllowHexSpecifier)
.
Also does uint.ToString()
convert to a decimal representation. Do you mean to convert to a hex? Then you should .ToString("X")
.
What you code does once the parsing is ok, is in complete contradiction to what you describe it's supposed to. You'll end up with [ "26", "7A", "60", "60" ], where "26" is the (decimal) representation of 0x3A ^ 0x20, twenty-six.
Why are you messing with strings in the first place? Can't you just use a byte[]
? Like:
public static byte[] EscapeFix(byte[] receivedBytes)
{
return receivedBytes.Select(b => (byte)(b ^ 0x20)).ToArray();
}
Upvotes: 1