-1

Homework time again. I have to create a program to print 1s and 2s complement of a binary number. So far is tis correct for 2s compliment? Should I allow input, then calculate 1's compliment before 2's?

import java.util.Scanner;
public class BitWiseComplement {
    public static void main (String [] args) {

        String a = "1";
        String b = "0"; 

        Scanner reader = new Scanner(System.in);
        String binary; 
        String binary2; 

        System.out.println("Please enter your binary number:");
        binary = reader.nextLine(); 

        binary2 = binary.replaceAll(a, b);

        System.out.println(binary2);
        }
    }
user2913004
  • 123
  • 1
  • 3
  • 8

2 Answers2

0

For 1's complement of an integer you can 1st convert the integer to binary using Integer class library method toBinaryString() and then run a loop and convert 1's to 0 and vice-versa.

void firstcomplement(int num)
{
    String binary=Integer.tobinaryString(num);
    String complement="";
    for(int i=0; i<binary.length(); i++)
    {
         if(binary.charAt(i)=='0')
             complement[i] += "1";
         if(binary.charAt(i)=='1')
             complement[i] += "0";
    }

 }
-1

Try:

String s3=String.format("%4s", 
              Integer.toBinaryString(i1))
                     .replace(' ', '0')
                     .replace('0' ,'a')
                     .replace('1' ,'0')
                     .replace('a' ,'1');

and then add one to it.

NASSER
  • 5,900
  • 7
  • 38
  • 57