Converting integer to a bit representation

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

    Doesn't work with negatives.

    vector convert(int x) {
      vector ret;
      while(x) {
        if (x&1)
          ret.push_back(1);
        else
          ret.push_back(0);
        x>>=1;  
      }
      reverse(ret.begin(),ret.end());
      return ret;
    }
    

提交回复
热议问题