Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

C# string to byte function

In converter.telerik.com I converted a function and got the code below

I am getting an error on this line
 yKey = new byte[sHex.Length / (double)2 - 1 + 1];

Open in new window



  private byte[] ConvertHex(string sHex)
{
    byte[] yKey;

    try
    {
        yKey = new byte[sHex.Length / (double)2 - 1 + 1];
        int i = 0;
        int j = 0;

        while (j < yKey.Length)
        {
            yKey[j] = Convert.ToByte(sHex.Substring(i, 2), 16);
            i += 2;
            j += 1;
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message, e);
    }

    return yKey;
}

Open in new window

Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

You have GetBytes method built in which does exactly what you're trying to achieve.
Avatar of Larry Brister

ASKER

JOnathan,
Which I would use how with my string I am passing in? (sHex)
Like this perhaps:
using System;

namespace EE_Q29215493
{
    class Program
    {
        static void Main(string[] args)
        {
            var bytes = "43480170".ConvertHex();
            Console.WriteLine($"Byte Array: [ {string.Join(", ", bytes)} ]");
            Console.ReadLine();
        }
    }

    static class Extensions
    {
        public static byte[] ConvertHex(this string hex)
        {
            uint num = uint.Parse(hex, System.Globalization.NumberStyles.AllowHexSpecifier);

            return BitConverter.GetBytes(num);
        }
    }
}

Open in new window

Produces the following output:
User generated image
HTH,

-saige-
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Which I would use how with my string I am passing in? (sHex)

byte[] bytes = Encoding.GetBytes(sHex);

Open in new window


Note, you cannot convert a string to a byte, because a string is a sequence of characters. Therefor, you can convert it to a sequence of bytes, whereas each character is representing a single byte. If you need a specific encoding map, you can browse the inherited methods in the doc.