迭代char的位

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

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

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

你可以优化它(如评论中所建议):

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

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

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

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

只需在您关心的每个位置使用按位检查。 类似下面的内容将创建一个包含各个值的数组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; } 

您必须通过按位操作执行此操作:

即:

 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。

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

展开循环:

 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;