Archived

This topic is now archived and is closed to further replies.

Convert decimal to string of Binary digits

This topic is 5177 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

// I''m trying to convert and INT/UINT to a binary string. // Does anyone have a better way to do this? void PrintBin(unsigned u) { unsigned uCNT = 0, // bit in string (start with first) uSHL = 31; // bit to test (start with last) char szBits[33] = {0}; // string of bits // test each bit for off (48 == ''0'') or on (49 == ''1'') while (32 > uCNT) szBits[uCNT++] = (u & (1 << uSHL--) ? 49 : 48); // print the string of bits cout << szBits << ''\n''; } // My code looks like words I can''t say in public forums; // Please advise, thnx

Share this post


Link to post
Share on other sites
Look on here for probably the easiest way to do it. Make a std::ostringstream, and use the iomanipulators to set the base to 2. then use the str() method to get the string... or str().c_str() if you want a C String. BTW, that site uses unqualified access to namespace std... so either qualify the manipulators (preferable)... or do a using directive.

EDIT: Info about namespace

[edited by - dmounty on October 11, 2003 7:39:02 PM]

Share this post


Link to post
Share on other sites
thnx dmounty...

...but that just doesn''t seem to be a better conversion method.
The printing of the string is not important to me so I''m really only concerned with a clear function that others can step through to understand the process if necessary.

-c3019

Share this post


Link to post
Share on other sites
Well if its just for someone to step through and understand how it works... it seems quite clear whats going on. It illustrates the use of the post increment and bitshift operators very nicely too.

EDIT: missed a word out :S

[edited by - dmounty on October 11, 2003 8:18:06 PM]

Share this post


Link to post
Share on other sites