2012-04-08 72 views
1

我想知道你将如何改变二进制数和反向的1和0?我知道如何改变一个整数转换成二进制已经的Java:更改二进制数位的0比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); 
    } 
} 

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

+2

并解释什么是与您当前密码的问题。 – Mahesh 2012-04-08 22:48:42

+0

注意到是错我的代码,到目前为止,我只需要在扭转二进制数例帮助:101 = 010 – TriggerLess 2012-04-08 22:55:42

回答

3

使用按位不起作用~

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

谢谢,我会尝试,现在 – TriggerLess 2012-04-08 22:53:54

4

你并不需要明确地将其转换为二进制文件。您可以使用bitwise operators

+0

谢谢,会尝试这种现在 – TriggerLess 2012-04-08 22:55:58

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

应该这样做。

+1

那么,如果它是一个十六进制,那么它应该是parseInt(十六进制,16),不应该吗? – 2012-04-08 22:52:54

+0

OP使用十六进制表示字符串输入。你是对的,它应该有一个更好的名字。 – scientiaesthete 2012-04-08 22:54:27

相关问题