Perform binary addition and subtraction with a signed binary numbers in Java -
for pure enjoyment , on time, i'm trying learn more binary numbers , assembly. have been local library checking out books in order gain more understanding of binary numbers , addition. didn't know before few weeks back, 1 add binary numbers java. i'm stumbled , have been 2 days on this.
like said i'm trying add binary numbers in addition , subtraction. i'm assuming need parse in order work properly. feel i'm on looking here. missing? helpful.
as of right now, have this:
`import java.util.scanner; public class binary operation { public static void main(string[]args){ scanner keyboard = new scanner(system.in); boolean keepgoing = true; string binary1, binary2; int num1, num2; system.out.println("scenario: choose (a)dd, (s)ubtract, (e)xit"); char choice = keyboard.next().charat(0); while(keepgoing){ if (choice == 'a' || choice == 'a'){ system.out.println("enter 8-bit signed binary number: "); binary1 = keyboard.next(); system.out.println("enter binary number: "); binary2 = keyboard.next(); num1 = integer.parseint(binary1, 2); num2 = integer.parseint(binary2, 2); int sum = num1 + num2; system.out.println(integer.tobinarystring(sum)); } else if(choice == 's' || choice == 's'){ system.out.println("enter 8-bit signed binary number: "); binary1 = keyboard.next(); system.out.println("enter binary number: "); binary2 = keyboard.next(); num1 = integer.parseint(binary1, 4); num2 = integer.parseint(binary2, 4); int difference = num1 - num2; system.out.println(integer.tobinarystring(difference)); } else if(choice == 'e' || choice == 'e'){ system.out.println("thank you."); keepgoing = false; system.exit(0); } if(keepgoing){ system.out.println("choose (a)dd, (s)ubtract, (e)xit"); choice = keyboard.next().charat(0); } }
the tobinarystring
prints 32-bit unsigned value. need method like.
public static string tosignedbinary(int num) { return num < 0 ? "-" + long.tobinarystring(-(long) num) : integer.tobinarystring(num); }
Comments
Post a Comment