开发者

how to convert hexadecimal from string in c#

i have a string which contains hexadecimal values i want to know how to convert that string to hexadecimal开发者_运维问答 using c#


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.


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;
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜