How to convert UCHAR to Binary
I want to know how to convert a UCHAR array to a binary string in C++/MFC.
I tried some 开发者_C百科of the possibilities with Cstring but they didn't work. Please let me know why.
Here is the code which I have tried:
UCHAR ucdata[256];
ucdata[0] = 40;
char data[100];
StrCpy(data,(char *)ucData);
CString dataStr(data);
// original value
// convert to int
int nValue = atoi( dataStr );
// convert to binary
CString strBinary;
itoa( nValue, strBinary.GetBuffer( 50 ), 2 );
strBinary.ReleaseBuffer();
C++ ... MFC CString
surely isn't it ...
In standard C++, you could do:
UCHAR ucdata[256];
ostringstream oss(ostringstream::out);
ostream_iterator<UCHAR> out(oss);
oss << setbase(2) << setw(8) << setfill('0');
copy(ucdata, ucdata + sizeof(ucdata), out);
cout << oss.str() << endl;
I'm not sure though how to convert this into MFC, altough if there exist converters between std::string
classes and MFC CString
then you might try to use those ?
You could try something like this (but note that itoa
isn't strictly portable):
UCHAR ucdata[256]; // filled somehow
CString result; // starts out empty
char buf[9]; // for each number
for (size_t i = 0; i < 256; ++i)
result += itoa(ucdata[i], buf, 2);
I don't know CString
, but if it's like a std::string
then you can append null-terminated C-strings simply with the +
operator.
精彩评论