65,186
社区成员




include <iostream>
#include <string>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
int
main(int argc, char *argv[])
{
uint32_t u1, u2;
string s;
u1 = 1234;
s.assign((char *)&u1, sizeof(u1));
memcpy(&u2, s.data(), sizeof(u2));
printf("u1=%d, u2=%d\n", u1, u2);
return 0;
}
std::basic_string::c_str
const CharT* c_str() const;
Returns a pointer to a null-terminated character array with data equivalent to
those stored in the string.
The pointer is such that the range [c_str(); c_str() + size()] is valid and the
values in it correspond to the values stored in the string with an additional
null character after the last position.
The pointer obtained from c_str() may be invalidated by:
Passing a non-const reference to the string to any standard library function,
or Calling non-const member functions on the string, excluding operator[],
at(), front(), back(), begin(), rbegin(), end() and rend().
Writing to the character array accessed through c_str() is undefined behavior.
#include <iostream>
#include <string>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
int
main(int argc, char *argv[])
{
unsigned i;
uint32_t u1, u2;
string s("ABCDXYZ0123456789");
u1 = 0x1234abcd;
s.insert(0, (char *)&u1, sizeof(u1));
memcpy(&u2, s.data(), sizeof(u2));
printf("u1=%x, u2=%x\n", u1, u2);
for (i = 0; i < s.size(); ++i) {
printf("%02x ", (unsigned char)s[i]);
}
printf("\n");
u1 = 0x9876ff2d;
s.replace(0, sizeof(u1), (char *)&u1, sizeof(u1));
memcpy(&u2, s.data(), sizeof(u2));
printf("u1=%x, u2=%x\n", u1, u2);
for (i = 0; i < s.size(); ++i) {
printf("%02x ", (unsigned char)s[i]);
}
printf("\n");
return 0;
}
/* 输出:
u1=1234abcd, u2=1234abcd
cd ab 34 12 41 42 43 44 58 59 5a 30 31 32 33 34 35 36 37 38 39
u1=9876ff2d, u2=9876ff2d
2d ff 76 98 41 42 43 44 58 59 5a 30 31 32 33 34 35 36 37 38 39
*/
/*
大端的机器,输出会有差异
*/