By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

assign char to std::string changes the char itself?

P: 27
Dear Friends,

I don't even really know how to describe this problem. My base64 decoding algorithm doesn't work fine, because the result of the following lines is 0xffffffc5 instead of 0xc5.

Please tell me how can I get in/out the string the original 0xc5 value and why is it going that way.

Thank you!

The code:
Expand|Select|Wrap|Line Numbers
  1. std::string t1;
  2. char* x = new char[1];
  3. x[0] = 0xc5;
  4. t1.append(x);
  5. fprintf(stderr, "0x%x ", t1[0]);
  6. return 0;
Jun 6 '07 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197
Part of your problem is that 0xc5 is 192. Your char can hold 127. More than that, it overflows and due to 2's complement is preceived as a very large negative number.

However, you should write this in C++:

Expand|Select|Wrap|Line Numbers
  1. stringstream ss;
  2. ss <<0xc5;    //put int value into stream
  3. string str;
  4. ss >> str;      //extract int as a string
  5. ss.clear();     //reset stream by clearing failbit 
  6. ss.seekp(0, ios::beg);  //and positioning to beginning of stream
  7. ss << str;       //re-insert the string
  8. int result = 0;
  9. ss.seekg(0, ios::beg);   //position to beginning of stream
  10. ss >> result;                //and extract integer
Jun 6 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.