1

In C++:

If I want to add 0x01 to the string text I would do: text += (char)0x01;

If I want to add 0x02 to the string text I would do: text += (char)0x02;

If I want to add 0x0i (were i is an unsinged int between 0 and 9), what could I do?

EDIT: I probably wasn't quite clear. So by 0x01, I mean the character given in Hex as 01. So in the above if i is the integer (in decimal) say 3, then I would want to add 0x03 (so this is not the character given in decimal as 48 + 3).

2
  • What is the type of text? What are you trying to accomplish? Commented Jun 10, 2012 at 0:33
  • @dirkgently: text is a string. So I want to add too the string (i.e. make it longer by one character) the character given in hex by 0i. Commented Jun 10, 2012 at 0:36

3 Answers 3

4

You can directly do

text += (char)i;

Because 0x0i == i if i is between 0 and 9.

Sign up to request clarification or add additional context in comments.

Comments

1

One other possibility -- you could use push_back instead. Since it takes the string's char_type as its parameter type, you don't need an explicit cast:

text.push_back(i);

In fairness, I should add that you don't really need an explicit cast with += either. Simply text += i; will work fine. For example:

std::string text; 
for (int i=0; i<9; i++)
     text += i;

With either text += i; or text.push_back(i);, this will produce a string that contains: "\x00\x01\x02\x03".

Comments

0

You should generate its ASCII value. '0' is 48 and '9' is 9 + 48

text += (char)( i + 48 ) ;

if i was a multi digit number you could parse it to its digits and use the same technique to generate its equal string.

2 Comments

He doesn't want 'i', he wants i, so there's no need to add to 48. That's why his samples are text += (char)0x01, and not text += (char)0x01+48
If you are right, so what's the point of this question ? I think his first 2 lines are not correct. He wanted to concatenate characters but his hexadecimal numbers says you are right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.