2016-06-14 60 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;