Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Decimal to binary conversion and vice versa

807606Feb 4 2007 — edited Feb 5 2007
Hi my assignment is to convert the users input from binary to decimal or decimal to binary depending on the users input. If the user inputs a binary string my program should return decimal equivalents, whether the input is signed magnitude, one's complement, or two's complement. So far my program only works for unsigned input.

So the question is what should I do to have the program return equivalents if the user enters a binary string in signed magnitude format, one's complent, or two's complement?



import java.util.*;
public class programming1
{
    public static void main(String[]args)
    {
        String x;
        
        Scanner keyboard = new Scanner(System.in);
        
        System.out.println("Enter one of two types of input: \n"
                           + "An 8-bit string or a decimal "
                           + "integer (-128, + 127): ");
        x = keyboard.next();
        
        if (x.length() == 8)
        {
            System.out.println("The decimal equivalent of " + x
                               + " is " + Integer.parseInt(x, 2));
        }
        else
        {
            byte y = (byte)Integer.parseInt(x);
            System.out.println("The binary equivalent of " + x
                               + " is " + Integer.toBinaryString(y));
        }
      
    }

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 5 2007
Added on Feb 4 2007
5 comments
1,024 views