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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With