How to pad bytes in java?

I need to add 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 bytes (or how to XOR it up to 11111111)?

Expected Result:

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

and the output should be 10000111, complementing (or XOR to 11111111)

+5
source share
3 answers

In addition to the byte, you are using an operator ~. Therefore, if x is 01111000, then it ~xis 10000111. For XORing, you can use x ^= 0xFF(11111111b == 0xFF in hexadecimal format)

+9
source

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

+1

If you have binary numbers like "111111", you can give two compliments without converting them to a number. You can do it.

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);
}
+1
source

All Articles