Author Topic: [snippet] data type to binary string  (Read 2400 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.
Secure the Source, Contain the Code, Protect the Project
chief1983

------------
funtapaz: Hunchon University biologists prove mankind is evolving to new, higher form of life, known as Homopithecus Juche.
z64555: s/J/Do
BotenAlfred: <funtapaz> Hunchon University biologists prove mankind is evolving to new, higher form of life, known as Homopithecus Douche.