Iterating bits of a char

爷,独闯天下 提交于 2020-01-02 03:25:46

问题


Assuming I have char "C" whose ascii code is 0110 0111. How can I iterate over its bits? I would like to build a vector from these 1's and 0's....


回答1:


You can easily iterate over them using bitwise operators:

char c = 'C';
for (int i = 0; i < 8; ++i)
{
  // extract the i-th bit
  int b = ((c & 1<<i) >> i);
  // b will be 1 if i-th bit is set, 0 otherwise

  // do whatever you want with b
}

you can optimize it (as suggested in comments):

int b = ((c >> i) & 1);



回答2:


A character has an integer value. Something like this will work :

 int myChar = 42;
 String binstr = Integer.toBinaryString(myChar);

The rest I'll leave to you as an exercise - but all you have to do now is iterate over the String representation of your binary value and do whatever it was that you planned on doing.




回答3:


Just use bitwise checks at each position you care about. Something like the following will create an array bits that holds the individual values.

char c = 'C';
int[] bits = new int[8];

int j = 0;
for(int i = 1; i <= 256; i *= 2){
    bits[j++] = (c & i) > 0 ? 1 : 0;
}



回答4:


You'll have to do this with bitwise operations:

ie:

while (my_char > 0) {
  if my_char & 1 
    char_vector.push 1 // if the right most bit is 1
  else 
    char_vector.push 0 // right most bit must be 0 if we fell through to the else
  my_char = my_char >> 1 // right shift one position
}

if you need to, you can pad the char_vector with the remaining 0s, after you right shift to zero.




回答5:


char c = 'C';
Vector<Boolean> vector = new Vector<Boolean>(16);
for (int i = Character.SIZE-1; i >=0; --i) {
    int num = c >> i;
    boolean set = (num & 1) == 1;
    vector.add(Boolean.valueOf(set));
}



回答6:


Unrolled loop:

int[] bits = new int[8]
bits[0] = (c & 1) > 0 ? 1 : 0;
bits[1] = (c & 2) > 0 ? 1 : 0;
bits[2] = (c & 4) > 0 ? 1 : 0;
bits[3] = (c & 8) > 0 ? 1 : 0;
bits[4] = (c & 16) > 0 ? 1 : 0;
bits[5] = (c & 32) > 0 ? 1 : 0;
bits[6] = (c & 64) > 0 ? 1 : 0;
bits[7] = (c & 128) > 0 ? 1 : 0;


来源:https://stackoverflow.com/questions/2480375/iterating-bits-of-a-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!