0

I have got this code from somewhere to convert hex string to normal string. But I cannot understand this. Can anybody explain this please ? In this string, The first line takes each two characters from the string and convert it to byte. But, I dont understand why they are assigning array to only half length of byte array ?

Sometimes it gets error too, i.e if Inputstring length is 350, byte length would be 175, and char length is 87.5, and char array is assigned to 87 only, thats not enough to hold all the characters in byte array.

public static string HextoString(string InputText)
{

    byte[] bb = Enumerable.Range(0, InputText.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(InputText.Substring(x, 2), 16))
                 .ToArray();
   //return Convert.ToBase64String(bb);
    char[] chars = new char[bb.Length / sizeof(char)];
    System.Buffer.BlockCopy(bb, 0, chars, 0, bb.Length);
    return new string(chars);
}

1 Answer 1

1

That is because .Where(x => x % 2 == 0) filters the input string to only those values, that have even indexes, so the output will have half the length of the original.

Sign up to request clarification or add additional context in comments.

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.