0

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;
}
2
  • Which language are you targeting? C#? Commented Jul 28, 2017 at 10:58
  • I am very confused about why your code seemingly discards Receivedbyte[0] and shuffles all of the rest one place down... Commented Jul 13, 2018 at 8:04

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.