开发者

Memcpy int to char buffer - as alternative to sprintf

#include <iostream>

using namespace std;

int main()
{
     char buffer[8];
     int field=534;
     memcpy(buffer,&field,sizeof(field));
     cout<<buffer<<endl;

     return 0;
}

This returns an empty buffer. Why?

Basically looking for an alternative to sprintf to convert int to char buffer.

Itoa is not available.

Thoughts? 开发者_StackOverflow社区 Better alternatives?


You will have to use sprintf or itoa to convert a binary int to an ascii string.

The representation if ints and and char arrays is totally different and ints can conytain bytes with a value of zero but strings can only have that as the last byte.

for example

Takes 0 - in int it is represented by 4 bytes with values 0 whilst ) as a string has the first two bytes of 48 and 0 so no simple cast will chnage this


I think the memcpy has succeeded. Memcopy is going to copy the bytes and not translate the bytes in to characters (as you want to do). You can't see because 534 happens to produce two non-printable characters. Try using 18505 and it'll print a message. Not what you want though.

If itoa isn't available then you could always write your own. In fact that's a common computer science homework problem. To do it you need to get each digit seperated from the integer (hint integer division will truncate - just what we want!) and you'll need to convert each digit from an integer between 0 and 9 and it's ascii representation.

That's enough hints but if you need more help then feel free to ask.


If itoa if available you can use it, this function is not not part of C++, but is supported by some compilers.

Alternatively you can do:

std::stringstream out;
out << field;
strcpy(buffer,out.str().c_str());


You can use also istringstream:

istringstream ss(field);
ss>>buffer;


Your method isn't going to work due to both the encoding of char's and the fact '9' != 9. But why not just build your own itoa? Its very simple(hint: x - '0' will turn '0' - '9' into 0 - 9), alternatively just copy the source for an itoa varient from any one of the open source libstdc's

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜