开发者

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 1000开发者_JAVA百科0111 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)


You need to write a loop to do it one byte at a time.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜