Question related to string in C#  
Author Message
cc2001a





PostPosted: Visual C# General, Question related to string in C# Top

Sorry to ask such noob question at here

if i got a string like this

string ss ="4a0368";

how to convert this stings ss to

byte[] test = {0x4a,0x03,0x68};

i am trying to use getbyte() but didn't work

test= ss.getbyte();

 or in short:

how to convert a string ss2 = "4a"; to byte 0x4a in C#



Visual C#7  
 
 
Matthew Watson





PostPosted: Visual C# General, Question related to string in C# Top

How about this:



using System.Globalization;

byte[] HexStringToByteArray(string hexString)
{
    if ((hexString.Length % 2) != 0)
    {
        throw new ArgumentOutOfRangeException
        (
            "hexString",
            hexString,
            "hexString must be a multiple of two characters long."
        );
    }

    int numBytes = hexString.Length/2;  // Two hex digits per byte.
    byte[] result = new byte[numBytes];

    for (int i = 0; i < numBytes; ++i)
    {
        result[ i ] = byte.Parse
        (
            hexString.Substring(i*2, 2), // Next 2 hex digits.
            NumberStyles.HexNumber
        );
    }

    return result;
}

 



 
 
cc2001a





PostPosted: Visual C# General, Question related to string in C# Top

Thanks for your suggestion.

byte.Parse( hexString.Substring(i*2, 2), NumberStyles.HexNumber );
This line solved my problem.

Thanks and Regards