user7339516
user7339516

Reputation: 33

convert java code to c# code (hexString To ByteArray)

Hello I have a code in Java I want to make it to code in C # but I'm having a problem:

This code (func):

DatatypeConverter.parseHexBinary (temp);

I'm looking for a replacement in C#

On the other hand I have the full code should do this in Java but also where I encountered a problem in this code:

public static byte [] hexStringToByteArray (String s)
{
    int len ​​= s.Length;
    byte [] data = new byte [len / 2];
    for (int i = 0; i <len; i + = 2)
    {
        data [i / 2] = (byte) ((Character.digit (s.charAt (i), 16) << 4)
                                     + Character.digit (s.charAt (i + 1), 16));
    }
    return data;
}

The problem is that the compiler does not recognize the

Character.digit (s.charAt (i)

Any help is appreciated. Thanks!

Upvotes: 2

Views: 1130

Answers (1)

ItamarG3
ItamarG3

Reputation: 4122

To convert a hex string to a byte array, you can use:

public static byte[] HexStringToByteArray(string s)
{
    int len = s.Length;
    byte[] data = new byte[len/ 2];
    for (int i = 0; i < len; i += 2)
    {
        data[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);
    }
    return data;
}

Upvotes: 1

Related Questions