Write a program to add two binary numbers in Java.
Before you start thinking about long binary arithmetic operation, be happy for the fact that Java has inbuilt mechanism for writing binary literals and displaying a number in binary.
If we prefix a number with 0b, the number will be treated as binary literal.
e.g.
int num1 = 0b1110;/* binary value*/
int num2 = 0b0001;
To convert a number to binary - or to display a number in binary, we can use the method toBinaryString() in Integer class.
int a = 10;
String st = Integer.toBinaryString(a);/*st is 1010*/
Now we just write a simple program to add two binary literals and display the answer in binary.
public class Demo { public static void main(String args[]) { int m = 0b110011; int n = 0b101100; int ans = m+n; System.out.println("The sum of two numbers is "+Integer.toBinaryString(ans)); } }
For these, you can use format() method of String class. %x will format the number in hexadecimal and %o will format the number in octal.
e.g.
int a =27;
String str1 = String.format("%x",a);//str1 will be 1b
String str2 = String.format("%o",a);//str2 will be 33
If we want a prefix of 0x to appear in the output, we can use
String str1 = String.format("a is 0x%x",a);
Now str1 will be a is ox1b
Comments
Post a Comment