Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 627
Ran Gualberto Avatar asked Aug 31 '11 12:08

Ran Gualberto


3 Answers

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)

like image 192
king_nak Avatar answered Oct 16 '22 19:10

king_nak


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

like image 20
Hot Licks Avatar answered Oct 16 '22 19:10

Hot Licks


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);
}
like image 1
Peter Lawrey Avatar answered Oct 16 '22 17:10

Peter Lawrey