C++中常用std::stoi和std::stringstream將十六進(jìn)制字符串轉(zhuǎn)為十進(jìn)制整數(shù)。1. 使用std::stoi時(shí),指定基數(shù)16可直接轉(zhuǎn)換無前綴的十六進(jìn)制字符串,如"1A"轉(zhuǎn)為26;若字符串含"0x"前綴(如"0x1A"),可將基數(shù)設(shè)為0,std::stoi會(huì)自動(dòng)識(shí)別進(jìn)制。2. 使用std::stringstream需結(jié)合std::hex,通過流操作將字符串解析為十進(jìn)制值,適用于需要靈活處理多種進(jìn)制的場(chǎng)景。3. 實(shí)際應(yīng)用中應(yīng)添加異常處理,捕獲std::invalid_argument(非法字符)和std::out_of_range(數(shù)值溢出)異常,確保程序健壯性。推薦優(yōu)先使用std::stoi,簡(jiǎn)潔高效,復(fù)雜場(chǎng)景選用stringstream。
在C++中,將十六進(jìn)制字符串轉(zhuǎn)換為十進(jìn)制整數(shù)有多種方法,最常用的是使用標(biāo)準(zhǔn)庫中的 std::stoi 或 std::stringstream。下面介紹幾種實(shí)用且清晰的實(shí)現(xiàn)方式。
std::stoi 支持自動(dòng)識(shí)別十六進(jìn)制格式(以 "0x" 或 "0X" 開頭),也可以通過參數(shù)指定基數(shù)。
示例代碼:
#include <string>
#include <iostream>
int main() {
????std::string hex_str = "1A";
????int decimal = std::stoi(hex_str, nullptr, 16);
????std::cout << "十六進(jìn)制 " << hex_str << " 轉(zhuǎn)為十進(jìn)制是 " << decimal << std::endl;
????return 0;
}
輸出結(jié)果:
十六進(jìn)制 1A 轉(zhuǎn)為十進(jìn)制是 26
說明:第三個(gè)參數(shù) 16 表示按十六進(jìn)制解析字符串,無需加 "0x" 前綴也能正確轉(zhuǎn)換。
立即學(xué)習(xí)“C++免費(fèi)學(xué)習(xí)筆記(深入)”;
利用 std::stringstream 和操作符 std::hex,可以更靈活地處理輸入。
示例代碼:
#include <sstream>
#include <string>
#include <iostream>
int main() {
????std::string hex_str = "1A";
????std::stringstream ss;
????int decimal;
????ss << std::hex << hex_str;
????ss >> decimal;
????std::cout << "十進(jìn)制值為:" << decimal << std::endl;
????return 0;
}
這種方式適合在需要混合處理多種進(jìn)制時(shí)使用。
新一代 AI 字幕工作站,為創(chuàng)作者提供字幕制作、學(xué)習(xí)資源、會(huì)議記錄、字幕制作等場(chǎng)景,一鍵為您的視頻生成精準(zhǔn)的字幕。
如果輸入包含 "0x",比如 "0x1A",上面的方法依然有效。
使用 std::stoi 示例:
std::string hex_str = "0x1A";
int decimal = std::stoi(hex_str, nullptr, 0); // 基數(shù)設(shè)為 0,自動(dòng)識(shí)別
當(dāng)?shù)谌齻€(gè)參數(shù)為 0 時(shí),std::stoi 會(huì)根據(jù)前綴自動(dòng)判斷進(jìn)制(0x 表示十六進(jìn)制,0 表示八進(jìn)制,否則為十進(jìn)制)。
實(shí)際使用中應(yīng)檢查輸入是否合法,避免程序崩潰。
例如:
try {
????std::string input = "GHI"; // 非法十六進(jìn)制字符
????int value = std::stoi(input, nullptr, 16);
} catch (const std::invalid_argument& e) {
????std::cout << "無效參數(shù):不是合法的十六進(jìn)制字符串" << std::endl;
} catch (const std::out_of_range& e) {
????std::cout << "數(shù)值超出范圍" << std::endl;
}
加上異常處理能提升程序穩(wěn)定性。
基本上就這些。選擇 std::stoi 最簡(jiǎn)潔,stringstream 更適合復(fù)雜場(chǎng)景,注意處理異常和非法輸入即可。
以上就是c++++中如何將十六進(jìn)制轉(zhuǎn)為十進(jìn)制_c++十六進(jìn)制轉(zhuǎn)十進(jìn)制方法的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
c++怎么學(xué)習(xí)?c++怎么入門?c++在哪學(xué)?c++怎么學(xué)才快?不用擔(dān)心,這里為大家提供了c++速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)