Off-Topic Discussion > Programming

[snippet] data type to binary string

(1/1)

z64555:
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: ---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;
}
--- End code ---

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.

Navigation

[0] Message Index

Go to full version