Java:将二进制数字位0更改为1,将1更改为0

时间:2012-04-08 22:46:43

标签: java

我想知道如何更改二进制数并反转1和0?我知道如何将整数转换为二进制数

Example 1: 5 as a parameter would return 2
Steps: 5 as a binary is 101
          The complement is 010
          010 as an integer is 2

将整数更改为二进制数的代码

import java.io.*;
public class DecimalToBinary{
  public static void main(String args[]) throws IOException{
  BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the decimal value:");
  String hex = bf.readLine();

  int i = Integer.parseInt(hex);  


  String bynumber = Integer.toBinaryString(i);


  System.out.println("Binary: " + bynumber);
  }
} 

如果有人请帮忙,谢谢!

3 个答案:

答案 0 :(得分:4)

您无需将其显式转换为二进制文件。您可以使用bitwise operators

答案 1 :(得分:3)

使用按位非函数~

int num = 0b10101010;
System.out.println(Integer.toBinaryString(num));         // 10101010
System.out.println(Integer.toBinaryString((byte) ~num)); //  1010101 (note the absent leading zero)

答案 2 :(得分:3)

int i = Integer.parseInt(numString);
i = ~i;

应该这样做。