迭代一个char的位

时间:2010-03-19 20:23:54

标签: java bit-manipulation

假设我有一个字符“C”,其ascii代码是0110 0111。我怎样才能迭代它的位?我想从这些1和0构建一个向量....

6 个答案:

答案 0 :(得分:13)

您可以使用按位运算符轻松迭代它们:

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
}

您可以对其进行优化(如评论中所示):

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

答案 1 :(得分:2)

字符具有整数值。这样的事情会起作用:

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

其余的我会留给你作为练习 - 但你现在要做的就是迭代你的二进制值的字符串表示,并做你计划做的任何事情。

答案 2 :(得分:2)

只需在您关心的每个位置使用按位检查。类似下面的内容将创建一个包含各个值的数组bits

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;
}

答案 3 :(得分:0)

您必须使用按位操作执行此操作:

即:

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
}

如果需要,可以在右移到零之后用剩余的0填充char_vector。

答案 4 :(得分:0)

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));
}

答案 5 :(得分:0)

展开循环:

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;