0
votes

I want to know how to convert a UCHAR array to a binary string in C++/MFC.

I tried some 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();
2
Why don't you show what you are trying to do in more detail (why), and also show what you have tried? - crashmstr
Show us your code, and tell us your expectations. - Kerrek SB
This might well be a dup of: stackoverflow.com/questions/708114/… - FrankH.
Hi, i have updated quest with my code please help - Naruto
Do you want a textual binary printout of your UCHAR array? In that case, could you be convinced to accept a hexadecimal printout? It'll be only 25% the size. - Kerrek SB

2 Answers

3
votes

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 ?

0
votes

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.