2016-06-14 58 views
0

我應該如何將一個整數添加到十六進制字符串中。用十六進制字符串添加整數

說我的十六進制字符串是:

11'h000 

我想整數7添加到它。輸出應該是

11'h007 

如果給出11'h00e,給它加整數1應該給我11'h00f。

C++中是否有任何預定義的函數?我可以編寫我的switch-case語句來獲得它,但尋找一個緊湊的方式。

+3

看一看[性病:: SOTI](http://www.cplusplus.com/reference/string/stoi/)和[性病:: to_string](HTTP:/ /www.cplusplus.com/reference/string/to_string/) – Garf365

+2

@ Garf365:即使在C++ 11中,您也無法輕易*使用std :: to_string輸出十六進制字符串。似乎最好的方式仍然是通過'std :: hex'流格式化程序。但我希望我錯了。 – Bathsheba

+0

@Bathsheba你說得對,最好的方法仍然是'std :: hex' – Garf365

回答

5

最好的方法是什麼?不要混淆數字的格式和數字。

使用

int x = std::stoi(s/*a hexadecimal string*/, nullptr, 16 /*hexadecimal*/); 
x++; /*all your arithmetic operations here*/ 
std::cout/*or a suitable stream*/ << std::hex << x;