1

我想知道您将如何更改二进制数并反转 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);
  }
} 

如果有人代码请帮忙,谢谢!

4

3 回答 3

4

您不需要将其显式转换为二进制。您可以为此使用按位运算符

于 2012-04-08T22:48:32.040 回答
3

使用按位非函数~

int num = 0b10101010;
System.out.println(Integer.toBinaryString(num));         // 10101010
System.out.println(Integer.toBinaryString((byte) ~num)); //  1010101 (note the absent leading zero)
于 2012-04-08T22:48:51.373 回答
3
int i = Integer.parseInt(numString);
i = ~i;

那应该这样做。

于 2012-04-08T22:51:30.327 回答