Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most light weight conversion from hex to byte in c#? [duplicate]

Tags:

c#

hex

byte

Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa?

I need an efficient and fast way to do this conversion. I have tried two different ways, but they are not efficient enough for me. Is there any other quick method to accomplish this in a real-time fashion for an application with huge data?

  public byte[] StringToByteArray(string hex)
    {
        return Enumerable.Range(0, hex.Length / 2).Select(x => Byte.Parse(hex.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray(); 
    }

The above one felt more efficient to me.

 public static byte[] stringTobyte(string hexString)
    {
        try
        {
            int bytesCount = (hexString.Length) / 2;
            byte[] bytes = new byte[bytesCount];
            for (int x = 0; x < bytesCount; ++x)
            {
                bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
            }
            return bytes;
        }
        catch
        {
            throw;
        }
like image 528
Mask Avatar asked Jan 15 '13 06:01

Mask


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

Is hex same as byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.

What is a byteArray?

A consecutive sequence of variables of the data type byte, in computer programming, is known as a byte array. An array is one of the most basic data structures, and a byte is the smallest standard scalar type in most programming languages.


1 Answers

If you really need efficiency then:

  • Don't create substrings
  • Don't create an iterator

Or, and get rid of try blocks which only have a catch block which rethrows... for simplicity rather than efficiency though.

This would be a pretty efficient version:

public static byte[] ParseHex(string hexString)
{
    if ((hexString.Length & 1) != 0)
    {
        throw new ArgumentException("Input must have even number of characters");
    }
    int length = hexString.Length / 2;
    byte[] ret = new byte[length];
    for (int i = 0, j = 0; i < length; i++)
    {
        int high = ParseNybble(hexString[j++]);
        int low = ParseNybble(hexString[j++]);
        ret[i] = (byte) ((high << 4) | low);
    }

    return ret;
}

private static int ParseNybble(char c)
{
    // TODO: Benchmark using if statements instead
    switch (c)
    {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            return c - '0';
        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
            return c - ('a' - 10);
        case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
            return c - ('A' - 10);
        default:
            throw new ArgumentException("Invalid nybble: " + c);
    }
    return c;
}

The TODO refers to an alternative like this. I haven't measured which is faster.

private static int ParseNybble(char c)
{
    if (c >= '0' && c <= '9')
    {
        return c - '0';
    }
    c = (char) (c & ~0x20);
    if (c >= 'A' && c <= 'F')
    {
        return c - ('A' - 10);
    }
    throw new ArgumentException("Invalid nybble: " + c);
}
like image 151
Jon Skeet Avatar answered Oct 17 '22 15:10

Jon Skeet