使用C#中的Convert.ToInt32()将十进制,八进制,十六进制字符串转换为整数

Convert.ToInt32()方法 (Convert.ToInt32() Method)

Convert.ToInt32() is a predefined method in C#, which returns an integer value (in 32 bits) from given various types of values.

Convert.ToInt32()是C#中的预定义方法,它从给定的各种类型的值中返回一个整数值(32位)。

Here, we will go with some of the conversion...

在这里,我们将进行一些转换...

Syntax:

句法:

    Convert.ToInt32(input, base);

Here,

这里,

  • input is the input string that may contain variable format's value like decimal/number value, octal value or hexadecimal value.

    输入是可能包含可变格式的值(例如十进制/数字值,八进制值或十六进制值)的输入字符串。

  • base is the number system base like, 10 for decimal (which we do not need to write while calling the function), 8 for octal and 16 for the hexadecimal value.

    base是一个数字系统的基数,例如10代表十进制 (调用函数时不需要写), 8代表八进制16代表十六进制值

Code:

码:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            int num = 0;
            try
            {
                input = "12345"; //value is a decimal formatted number
                num = Convert.ToInt32(input); //base is an optional if string contains decimal value 
                Console.WriteLine("num (decimal string to integer) :" + num);
                //we can also provide the base of the input - it is decimal value 
                //so, 10 can be used as base 
                num = Convert.ToInt32(input, 10);
                Console.WriteLine("num (decimal string to integer) :" + num);

                //convert octal string to integer
                input = "30071";
                num = Convert.ToInt32(input, 8);
                Console.WriteLine("num (octal string to integer) :" + num);

                //convert hex string to integer
                input = "3039ACFE";
                num = Convert.ToInt32(input, 16);
                Console.WriteLine("num (hex string to integer) :" + num);                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

输出量

num (decimal string to integer) :12345
num (decimal string to integer) :12345
num (octal string to integer) :12345
num (hex string to integer) :809086206


翻译自: https://www.includehelp.com/dot-net/converting-decimal-octal-hexadecimal-string-to-integer-using-Convert-ToInt32-in-c-sharp.aspx

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值