C# Split HexString

Well, I got my HexString (PacketS) for example "70340A0100000000000000" I want to split every time after 2 chars and put it into an byte array (Stream).

Means {70, 34, 0A, 01, 00, 00, 00, 00, 00, 00, 00}


The shortest path (.NET 4+) is (depending the length or origin):

byte[] myBytes = BigInteger.Parse("70340A0100000000000000", NumberStyles.HexNumber).ToByteArray();
myStram.write(myBytes, 0, myBytes.Length);

For previous versions string.length/2 also defines the length of a byte array than can be filled for each parsed pair. This byte array can be written on stream as above.

For both cases, if your origin string is too long, and you want to avoid a huge byte array, proceed with steps getting groups of N characters from your origin.

This actually worked perfect! I am sorry if your code does the same but I just do not understand.

public static byte[] ConvertHexStringToByteArray(string hexString)
            if (hexString.Length % 2 != 0)
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));

            byte[] HexAsBytes = new byte[hexString.Length / 2];
            for (int index = 0; index < HexAsBytes.Length; index++)
                string byteValue = hexString.Substring(index * 2, 2);
                HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);

            return HexAsBytes;

Need Your Help

What is an "misaligned image" in terms of Core Animation in iPhone OS?

iphone cocoa-touch uikit core-animation instruments

Instruments tells that there are "misaligned images" which are animated by core animation. What does that mean?

Nullable dateTimePicker

c# winforms datetimepicker

I would like the user to set the DateTimePicker to Null when I hide it. I have written a code but it only shows the year portion '00' and shows tomorrow's date. Like "01-Jan-00". I want the whole d...