技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營(yíng)

贊助商

分類目錄

贊助商

最新文章

搜索

[示例]C#將十六進(jìn)制字符串轉(zhuǎn)換為整數(shù)

作者:admin    時(shí)間:2022-5-27 22:2:24    瀏覽:

在前面文章中,分別介紹了C#把二進(jìn)制字符串轉(zhuǎn)換為整數(shù),C#把八進(jìn)制字符串轉(zhuǎn)換為整數(shù),今天,將介紹C#是如何將十六進(jìn)制字符串轉(zhuǎn)換為整數(shù)的。

給定一個(gè)十六進(jìn)制數(shù)作為輸入,我們需要編寫一個(gè)程序?qū)⒔o定的十六進(jìn)制數(shù)轉(zhuǎn)換為等效的整數(shù)。要將十六進(jìn)制字符串轉(zhuǎn)換為整數(shù),我們必須使用Convert.ToInt32()函數(shù)來(lái)轉(zhuǎn)換值。

句法:

Convert.ToInt32(input_string, Input_base);

這里,

  • input_string 是包含字符串格式的十六進(jìn)制數(shù)字的輸入。
  • input_base 是輸入值的基數(shù)——對(duì)于十六進(jìn)制值,它將是 16。

例子:

輸入:56304
輸出:353028

輸入:598f
輸出:22927

如果我們輸入錯(cuò)誤的值,例如。672g,它顯示錯(cuò)誤:

輸入一個(gè)十六進(jìn)制數(shù):System.FormatException:其他不可解析的字符位于字符串的末尾。

如果我們輸入大于 8 位的數(shù)字,例如 746465789,則會(huì)顯示錯(cuò)誤:

輸入十六進(jìn)制數(shù):System.OverflowException:算術(shù)運(yùn)算導(dǎo)致溢出。

示例1:

using System;
using System.Text;
  
class Program {
    
    static void Main(string[] args)
    {
        // 16進(jìn)制字符串
        string input = "56304";
        int output = 0;
        
        // 轉(zhuǎn)換為整數(shù)
        output = Convert.ToInt32(input, 16);
        
        // to print  the value
        Console.WriteLine("整數(shù): " + output);
    }
}

輸出:

整數(shù):353028

示例2:

using System;
using System.Text;
  
namespace webkaka {
    
class WKK {
    
    static void Main(string[] args)
    {
        string input = "";
        int output = 0;
        try {
            
            // 輸入字符串
            Console.Write("輸入一個(gè)十六進(jìn)制數(shù): ");
            input = Console.ReadLine();
  
            // 轉(zhuǎn)換為整數(shù)
            output = Convert.ToInt32(input, 16);
  
            Console.WriteLine("整數(shù): " + output);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        }
  
        // 按 ENTER 退出
        Console.ReadLine();
    }
}
}

輸入:

598f

輸出:

輸入一個(gè)十六進(jìn)制數(shù):
整數(shù):22927

總結(jié)

本文通過(guò)兩個(gè)示例,介紹了C#將十六進(jìn)制字符串轉(zhuǎn)換為整數(shù)的方法。其實(shí)句式并不復(fù)雜,不管是16進(jìn)制,8進(jìn)制,2進(jìn)制,都是有Convert.ToInt32()的一個(gè)參數(shù)決定的。套用句法,這個(gè)轉(zhuǎn)換程序并不難寫。

相關(guān)文章

x
  • 站長(zhǎng)推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */