Author Topic: [snippet] data type to binary string  (Read 639 times)

0 Members and 1 Guest are viewing this topic.

Offline z64555

  • 210
  • Self-proclaimed controls expert
    • Minecraft
    • Steam
[snippet] data type to binary string
This snippet converts an input type of size_t into a string with its binary representation. Might be useful if you need to watch a flag set, or maybe make a matrix-style background.

Code: [Select]
std::string binary_string(size_t input) {
        std::string buf;
        std::string retval = "0b";
        short rem;
        for (; input > 0; input >>= 1) {
                (input & 0x01) ? buf.push_back('1') : buf.push_back('0');
        rem = 8 - (buf.size() % 8);
        buf.append(rem, '0');
        retval.append(buf.rbegin(), buf.rend());
        return retval;

How it works:
The for loop right-shifts a copy of the input value into oblivion and pushes either a '1' or '0' into a buffer string, stopping at the input's msb. It then justifies the string to the nearest byte width and flips it around, since the string was made backwards. This particular version also prepends a "0b" identifier before the string to help readers recognize that it is a binary value.
I'm on Facebook! sort of. Zeesixtyfour Fivefiftyfive

R.I.P. Oliver
EveningTea: Time to go Freeman on this cultist..
* EveningTea pulls crowbar off his shoulderstrap and charges screaming incoherently across the marsh *
z64555: bro. do you even salad
z64555: suprise double quaternion!