简体   繁体   中英

How to complement bytes in java?

I need to complement string binaries.

st=br.readLine() //I used readline to read string line

byte[] bytesy = st.getBytes(); //and put it to bytes array.

Now how can I complement the binary equivalent of the bytes (or how to XOR it to 11111111) ?

Expected output :

If first char of st is x then binary equivalent is 01111000

and the output must be 10000111 by complementing ( or XOR to 11111111)

To complement a byte, you use the ~ operator. So if x is 01111000, then ~x is 10000111. For XORing you can use x ^= 0xFF (11111111b == 0xFF in hex)

您需要编写一个循环来一次执行一个字节。

If you have numbers as binary such as "111111" you can perform twos-compliment without converting it to a number. You can do this.

BufferedReader br = 
int ch;
while((ch = br.read()) >= 0) {
   switch(ch) {
      case '0': ch = '1'; break;
      case '1': ch = '0'; break;
   }
   System.out.print(ch);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM