Larry Brister
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
I am getting an error on this line
yKey = new byte[sHex.Length / (double)2 - 1 + 1];
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;
}
You have GetBytes method built in which does exactly what you're trying to achieve.
ASKER
JOnathan,
Which I would use how with my string I am passing in? (sHex)
Which I would use how with my string I am passing in? (sHex)
Like this perhaps:
HTH,
-saige-
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);
}
}
}
Produces the following output:HTH,
-saige-
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Which I would use how with my string I am passing in? (sHex)
byte[] bytes = Encoding.GetBytes(sHex);
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.