A
Alex Vinokur
typedef unsigned short u_short;
typedef unsigned char u_char;
u_short us1 = 0xabcd; // or u_short us1 = htons (0xabcd);
u_short us2 = 0xef; // or u_short us2= htons (0xef);
// ----- memcpy ---
u_char* buf = new (nothrow) u_char [512];
// Checking buf != 0
memcpy (&buf[0], (u_char*)us1, sizeof (us1));
memcpy (&buf[sizeof (us1), (u_char*)us2 sizeof (us2);
It works fine.
Now 'buf' contains the following bytes: ab-cd-00-ef
// ----- ostringstream ---
ostringstream oss;
oss << hex << setw (sizeof (u1) * 2) << setfill ((char*)0) <<
(u_char*) &us1
<< setw (sizeof (u2) * 2) << setfill ((char*)0) <<
(u_char*) &us2;
Of course, it doesn't work as memcpy, i.e. oss.str() doesn't contain
ab-cd-00-ef
It is because 'operator <<' is not memory-related operator, but
string-related one.
// ------------------------------
Nevertheless, is it possible to do via ostringstream (or via other
feature of C++) what we do via memcpy?
typedef unsigned char u_char;
u_short us1 = 0xabcd; // or u_short us1 = htons (0xabcd);
u_short us2 = 0xef; // or u_short us2= htons (0xef);
// ----- memcpy ---
u_char* buf = new (nothrow) u_char [512];
// Checking buf != 0
memcpy (&buf[0], (u_char*)us1, sizeof (us1));
memcpy (&buf[sizeof (us1), (u_char*)us2 sizeof (us2);
It works fine.
Now 'buf' contains the following bytes: ab-cd-00-ef
// ----- ostringstream ---
ostringstream oss;
oss << hex << setw (sizeof (u1) * 2) << setfill ((char*)0) <<
(u_char*) &us1
<< setw (sizeof (u2) * 2) << setfill ((char*)0) <<
(u_char*) &us2;
Of course, it doesn't work as memcpy, i.e. oss.str() doesn't contain
ab-cd-00-ef
It is because 'operator <<' is not memory-related operator, but
string-related one.
// ------------------------------
Nevertheless, is it possible to do via ostringstream (or via other
feature of C++) what we do via memcpy?