Hemant Bhargava
Hemant Bhargava

Reputation: 3575

Addition of an integer with an hex string

What should I do to add an integer to an hex string.

Say my hex string is:

11'h000

And I want to add integer 7 to it. Output it should give should be

11'h007

If given 11'h00e, Adding integer 1 to it should give me 11'h00f.

Are there any predefined functions in c++? I could have write my switch-case statements to get it but looking for a compact way.

Upvotes: 0

Views: 115

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

The best way? Don't confuse formatting of a number with a number.

Use

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;

Upvotes: 5

Related Questions