1

i have a string which contains hexadecimal values i want to know how to convert that string to hexadecimal using c#

2
  • 1
    Do you mean convert it into an integer? "hexidecimal" isn't a type. Commented Aug 4, 2010 at 5:05
  • 1
    There's no such thing as "hexadecimal values." Numbers are numbers, hex is just a representation. Ie: 0xff and 255 are the same number Commented Aug 4, 2010 at 5:05

2 Answers 2

2

There's several ways of doing this depending on how efficient you need it to be.

Convert.ToInt32(value, fromBase) // ie Convert.ToInt32("FF", 16) == 255

That is the easy way to convert to an Int32. You can use Byte, Int16, Int64, etc. If you need to convert to an array of bytes you can chew through the string 2 characters at a time parsing them into bytes.

If you need to do this in a fast loop or with large byte arrays, I think this class is probably the fastest way to do it in purely managed code. I'm always open to suggestions for how to improve it though.

0

Given the following formats

10A
0x10A
0X10A

Perform the following.

public static int ParseHexadecimalInteger(string v)
{
    var r = 0;
    if (!string.IsNullOrEmpty(v))
    {
        var s = v.ToLower().Replace("0x", "");
        var c = CultureInfo.CurrentCulture;
        int.TryParse(s, NumberStyles.HexNumber, c, out r);
    }
    return r;
} 

Not the answer you're looking for? Browse other questions tagged or ask your own question.