java 如何在java中补充字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7256637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to complement bytes in java?
提问by Ran Gualberto
I need to complement string binaries.
我需要补充字符串二进制文件。
st=br.readLine() //I used readline to read string line
st=br.readLine() //I used readline to read string line
byte[] bytesy = st.getBytes(); //and put it to bytes array.
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) ?
现在我如何补充字节的二进制等价物(或如何将它异或到 11111111)?
Expected output :
预期输出:
If first char of st is x then binary equivalent is 01111000
如果 st 的第一个字符是 x 那么二进制等价物是 01111000
and the output must be 10000111 by complementing ( or XOR to 11111111)
并且输出必须是 10000111 通过补码(或 XOR 到 11111111)
回答by king_nak
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)
要补充一个字节,您可以使用~
运算符。所以如果 x 是 01111000,那么~x
就是 10000111。对于异或,你可以使用x ^= 0xFF
(11111111b == 0xFF in hex)
回答by Hot Licks
You need to write a loop to do it one byte at a time.
您需要编写一个循环来一次执行一个字节。
回答by Peter Lawrey
If you have numbers as binary such as "111111" you can perform twos-compliment without converting it to a number. You can do this.
如果您有二进制数,例如“111111”,您可以执行二进制补码,而无需将其转换为数字。你可以这样做。
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);
}