-2

I want to convert from hex string to byte[] and i have this function:

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

When my string is for example "1234" this return byte[] but when my string is "12345" this failed due to Index and length must refer to a location within the string Why this is happening ?

  • possible duplicate of [How do you convert Byte Array to Hexadecimal String, and vice versa?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa) – rpax Jun 08 '14 at 16:02

2 Answers2

1

You could fix your input to be divisible by 2 adding a "0" char to the beginning of your string

public static byte[] StringToByteArray(string hex) 
{
    if((hex.Length % 2) != 0)
        hex = "0" + hex;

    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Without this 'fix' the current code fails. For example, assuming a string in the form "ABC" then the Where returns the position 0 and 2, that are passed as input to the Select and used in the Substring call. But this call, when tries to read two characters from position 2, raises the exception because there is just one char to read.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    An exception should be thrown if the string isn't even. Adding a zero to the beginning is just guessing. – Doug Jun 08 '14 at 16:14
  • So, by your comment, if the Poster has a string in the form "ABC" then it should accept the exception and tell its user to type the missing char? I disagree. – Steve Jun 08 '14 at 16:23
1

Not being familiar with lambdas, I would set the range to enumerate by two's and throw an exception if the string length is not evenly divisible by two.

Doug
  • 3,472
  • 3
  • 21
  • 18