3

Okay, A friend helped me with this code a little bit. I understand what everything else does and why it does it except for one thing. Where is this 128 coming from?? Also, this program runs, pulls the string from the file, converts it to binary, but takes all of the spaces out, so that when you re convert the binary back to the string, it is all one word. So what is the 128 and what can I do to keep the spaces?

/******************************* *I fixed it, Thanks for your help guys! * *I have changed the code so you can see how I fixed it. * *******************************/

         public static void main(String[] args) {

          String text = "My string to binary works too";

          byte[] bytes = text.getBytes();
          StringBuilder binary = new StringBuilder();

          for (byte b : bytes){
            int val = b;
          for (int i = 0; i < 8; i++){
            binary.insert(0, (val & 1) == 0 ? 0 : 1);
            val >>>= 1;
          }
            binary.insert(0, ' ');
         System.out.print(binary);
      }



      }

}

4

3 回答 3

1

128 是 2^7 次方,这意味着二进制是 10000000。字节由 8 位组成。因此,在使用 128 的行上,您正在执行按位 AND 以获得最高位。(然后在下一行,将值向左移动一位并重复,因此您从左到右依次获取每个位的值。)

于 2013-10-27T04:18:15.187 回答
0

正如其他人所说,128 只是 MSB 中 1 的位掩码。

如果您有一个字节为 10011001,请遵循逻辑:

10011001 & 10000000 = 10000000 != 0
11011001 << 1 = 00110010
00110010 & 10000000 = 00000000 == 0

and so on...

这是实现相同但相反的替代逻辑(LSB 中的掩码),并且可能更直接有意义:

int val = b;
for (int i = 0; i < 8; i++)
{
    binary.insert(0, (val & 1) == 0 ? 0 : 1);
    val >>>= 1;
}
binary.insert(0, ' ');

按照这个逻辑,你有:

10011001 & 00000001 = 00000001 != 0
11011001 >>> 1 = 01101100
01101100 & 00000001 = 00000000 == 0

and so on...
于 2013-10-27T04:52:11.467 回答
0

128 是二进制的 1000 0000,因此它是字节的最高有效位 (MSB)。MSB 是左边的第一个位。由于代码将位从 MSB 打印到 LSB,因此每次循环迭代都会打印 1 或 0,具体取决于 AND (&) 的结果,其值仅设置了 MSB 位 (128),并将值向左移动一位。

于 2013-10-27T04:23:51.007 回答