0

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();
6
  • Why don't you show what you are trying to do in more detail (why), and also show what you have tried? Commented Jun 23, 2011 at 12:18
  • 1
    Show us your code, and tell us your expectations. Commented Jun 23, 2011 at 12:18
  • This might well be a dup of: stackoverflow.com/questions/708114/… Commented Jun 23, 2011 at 12:40
  • Hi, i have updated quest with my code please help Commented Jun 23, 2011 at 12:41
  • 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. Commented Jun 23, 2011 at 12:44

2 Answers 2

3

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 ?

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.