Converting integer to a bit representation

后端 未结 6 2055
死守一世寂寞
死守一世寂寞 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:59

    Here is a version that works with negative numbers:

    string get_bits(unsigned int x)
    {
      string ret;
      for (unsigned int mask=0x80000000; mask; mask>>=1) {
        ret += (x & mask) ? "1" : "0";
      }
      return ret;
    }
    

    The string can, of course, be replaced by a vector or indexed for bit values.

提交回复
热议问题