Converting integer to a bit representation

后端 未结 6 2059
死守一世寂寞
死守一世寂寞 2020-12-09 11:30

How can I convert a integer to its bit representation. I want to take an integer and return a vector that has contains 1\'s and 0\'s of the integer\'s bit representation.

6条回答
  •  没有蜡笔的小新
    2020-12-09 11:58

    Returns a string instead of a vector, but can be easily changed.

    template
    std::string get_bits(T value) {
        int size = sizeof(value) * CHAR_BIT;
        std::string ret;
        ret.reserve(size);
        for (int i = size-1; i >= 0; --i)
            ret += (value & (1 << i)) == 0 ? '0' : '1';
        return ret;
    }
    

提交回复
热议问题