如何将十六进制值从字符串转换为int?

时间:2021-12-10 20:32:08

I have a string which typically is in the format : "0xFF". I'll trim it since there is a chance of whitespace.

我有一个字符串,通常格式为:“0xFF”。我会修剪它,因为有可能有空白。

How do i convert that into hex and convert "34" to decimal? I know about .Parse but does this support hex characters when the string is "0x123"?

如何将其转换为十六进制并将“34”转换为十进制?我知道.Parse但是当字符串是“0x123”时,它是否支持十六进制字符?

2 个解决方案

#1


You'll have to strip the "0x" part, but this snippet works:

您必须删除“0x”部分,但此代码段有效:

using System;
using System.Globalization;

public class StrToInt {
    public static void Main(string[] args) {
        string val = "FF";
        int num = Int32.Parse(val, NumberStyles.AllowHexSpecifier);
        Console.WriteLine(num);
    }
}

#2


int i = int.Parse( "FF", System.Globalization.NumberStyles.HexNumber );
MessageBox.Show( i.ToString() );  // displays 255

However, you will need to trim the leading "0x".

但是,您需要修剪前导“0x”。

#1


You'll have to strip the "0x" part, but this snippet works:

您必须删除“0x”部分,但此代码段有效:

using System;
using System.Globalization;

public class StrToInt {
    public static void Main(string[] args) {
        string val = "FF";
        int num = Int32.Parse(val, NumberStyles.AllowHexSpecifier);
        Console.WriteLine(num);
    }
}

#2


int i = int.Parse( "FF", System.Globalization.NumberStyles.HexNumber );
MessageBox.Show( i.ToString() );  // displays 255

However, you will need to trim the leading "0x".

但是,您需要修剪前导“0x”。