2 Ways to Add Binary Numbers in Java — Coding Example
In the last article, I have shown you how to subtract binary numbers in Java, and today, you will learn the opposite i.e. how to add binary numbers in Java. You can do binary addition in Java either by writing your own logic or by taking advantage of the Java API, which allows you to convert a binary string into a binary number. Though, if you want you can also use the logic I have shared in my earlier post about how to check binary numbers to verify input before converting it to a binary number. In this article, we’ll take a look at both methods of adding two binary numbers in Java. In this article, I have given you two solutions to add binary numbers in Java.
In the first solution, we have used the Java API, which first converts the given binary String to a decimal number using the Integer.parseInt() method, which is also used to convert String to Integer.
This method is overloaded to convert String to an integer in several other number systems e.b. binary, octal, decimal, and hexadecimal.
The overloaded version takes another int parameter radix, which you can use to convert a binary String to a decimal integer like Integer. parseInt ( number , 2 ), where the number is a String denoting a binary number. For example, String «101» will be converted into integer 5 and «1000» will be converted into 8.
Once you have got the number in decimal format, you can just add those numbers and convert the result to the binary String by using Integer.toBinaryString(sum);.
That’s all is needed if you use Java API as the first convert binary String to decimal numbers, add them and then convert the result back to binary form.
The second solution is a bit complex because we are actually doing the binary addition with binary numbers i.e. we are adding numbers from the right and then carrying the carry towards the left. It’s how you do in the paper. You can further check these free data structure and algorithms courses to learn more bout coding essentials like data structure, binary system, etc.
Java Program to add two binary numbers? Examples
Here is our complete solution of adding two binary numbers in Java. You can run this Java program into your favorite Java IDE like Eclipse or NetBeans or IntelliJIDEA, or even from a command prompt to add two given binary numbers.
import java.util.Scanner; /* * Java Program to add two binary numbers. * You can either write your own method or you * can use Java API for doing binary addition. * * input: 1010 + 101 * output = 1111 */ public class Main < public static void main(String[] args) < System.out.println("Welcome to Java program to add two binary numbers"); Scanner scnr = new Scanner(System.in); System.out.println("Please enter first binary number"); String first = scnr.nextLine(); System.out.println("Please enter second binary number"); String second = scnr.nextLine(); String addition = add(first, second); System.out.println("addition of two binary number is : " + addition); String sum = sum(first, second); System.out.println("Sum of two binary number is : " + sum); scnr.close(); > /** * Java method to calculate sum of two binary numbers this method calculate * sum by first converting binary String to binary numbers and then adding * them using binary arithmetic. * * @param first * @param second * @return sum of two given binary numbers */ public static String add(String first, String second) < int b1 = Integer.parseInt(first, 2); int b2 = Integer.parseInt(second, 2); int sum = b1 + b2; return Integer.toBinaryString(sum); > /** * Java method to add two binary numbers. This method doesn't use Java API, * instead develop it's own logic to perform binary addition. * * @param bin1 * @param bin2 * @return addition of two binary numbers */ public static String sum(String b1, String b2) < int len1 = b1.length(); int len2 = b2.length(); int carry = 0; String res = ""; // the final length of the result depends on the bigger length between b1 // and b, // (also the value of carry, if carry = 1, add "1" at the head of result, // otherwise) int maxLen = Math.max(len1, len2); for (int i = 0; i < maxLen; i++) < // start from last char of String b1 and b2 // notice that left side is an int and right side is char // so we need to minus the decimal value of '0' int p = i < len1 ? b1.charAt(len1 - 1 - i) - '0' : 0; int q = i < len2 ? b2.charAt(len2 - 1 - i) - '0' : 0; int tmp = p + q + carry; carry = tmp / 2; res = tmp % 2 + res; > return (carry == 0) ? res : "1" + res; > > Output Welcome to Java program to add two binary numbers Please enter first binary number 1010 Please enter second binary number 11 addition of two binary number is : 1101 Sum of two binary number is : 1101
If you are not sure how this program works, consider debugging this Java program by the instructions given in this article. When you debug the code inside the first method you can clearly see that Integer. parseInt(number, 2) converts a binary number into a decimal integer.
That’s all about how to write a Java program to add two binary numbers. You can use any of the methods to perform binary addition, but if you are asked in interviews, you should first use the Java way by using Integer.toString() method and then write your logic to calculate the sum of two binary numbers, if and only if Interviewer asked you to do so.
Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
Binary Literals
In Java SE 7, the integral types ( byte , short , int , and long ) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals:
// An 8-bit 'byte' value: byte aByte = (byte)0b00100001; // A 16-bit 'short' value: short aShort = (short)0b1010000101000101; // Some 32-bit 'int' values: int anInt1 = 0b10100001010001011010000101000101; int anInt2 = 0b101; int anInt3 = 0B101; // The B can be upper or lower case. // A 64-bit 'long' value. Note the "L" suffix: long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by one bit:
public static final int[] phases =
In hexadecimal, the relationship among the numbers is not readily apparent:
public static final int[] phases =
You can use binary integral constants in code that you can verify against a specifications document, such as a simulator for a hypothetical 8-bit microprocessor:
public State decodeInstruction(int instruction, State state) < if ((instruction & 0b11100000) == 0b00000000) < final int register = instruction & 0b00001111; switch (instruction & 0b11110000) < case 0b00000000: return state.nop(); case 0b00010000: return state.copyAccumTo(register); case 0b00100000: return state.addToAccum(register); case 0b00110000: return state.subFromAccum(register); case 0b01000000: return state.multiplyAccumBy(register); case 0b01010000: return state.divideAccumBy(register); case 0b01100000: return state.setAccumFrom(register); case 0b01110000: return state.returnFromCall(); default: throw new IllegalArgumentException(); >> else < final int address = instruction & 0b00011111; switch (instruction & 0b11100000) < case 0b00100000: return state.jumpTo(address); case 0b01000000: return state.jumpIfAccumZeroTo(address); case 0b01000000: return state.jumpIfAccumNonzeroTo(address); case 0b01100000: return state.setAccumFromMemory(address); case 0b10100000: return state.writeAccumToMemory(address); case 0b11000000: return state.callTo(address); default: throw new IllegalArgumentException(); >> >
You can use binary literals to make a bitmap more readable:
public static final short[] HAPPY_FACE =
How to Read and Write Binary Files in Java
In an earlier article, we looked at reading and writing different types of files in Java. In this short article, you will learn how to read and write binary files in Java.
The following example demonstrates how you can use the FileInputStream class to read a binary file, one byte at a time without any buffering:
try // create a reader FileInputStream fis = new FileInputStream(new File("input.dat")); // read one byte at a time int ch; while ((ch = fis.read()) != -1) System.out.print((char) ch); > // close the reader fis.close(); > catch (IOException ex) ex.printStackTrace(); >
If you are reading a large file, the above program may take some time to complete as it reads only one byte at a time. For better I/O performance, you should use the BufferedInputStream class as it reads a set of bytes all at once into an internal byte array buffer, reducing the number of calls to the disk, hence increasing I/O performance. By default, the internal buffer size is 8KB but we can specify a custom buffer size at the time of initialization. Here is an example that uses BufferedInputStream with default buffer size to read a binary file:
try // create a reader FileInputStream fis = new FileInputStream(new File("input.dat")); BufferedInputStream reader = new BufferedInputStream(fis); // read one byte at a time int ch; while ((ch = reader.read()) != -1) System.out.print((char) ch); > // close the reader reader.close(); > catch (IOException ex) ex.printStackTrace(); >
// custom buffer size int BUFFER_SIZE = 16 * 1024; // 16KB // create a reader FileInputStream fis = new FileInputStream(new File("input.dat")); BufferedInputStream reader = new BufferedInputStream(fis, BUFFER_SIZE);
If your binary file has encoding other the default character encoding of the operating system, or you want to explicitly set an encoding scheme, you have to use the InputStreamReader class instead:
try // create a reader FileInputStream fis = new FileInputStream(new File("input.dat")); // specify UTF_16 characer encoding InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_16); // read one byte at a time int ch; while ((ch = reader.read()) != -1) System.out.print((char) ch); > // close the reader reader.close(); > catch (IOException ex) ex.printStackTrace(); >
The following example shows how you can use the FileOutputStream class to write data to a binary file in Java:
try // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); // write data to file fos.write("Hey, there!".getBytes()); fos.write("\n".getBytes()); fos.write("How are you doing?".getBytes()); // close the writer fos.close(); > catch (IOException ex) ex.printStackTrace(); >
The above example works perfect but every time the write() method is called, an I/O operation to the disk is performed. It may not be a desirable solution for writing large-sized files. To reduce the number of I/O operations and improve performance, you should use the BufferedOutputStream class instead. Just like BufferedInputStream , it uses an internal buffer of size 8KB (can be customized) to store the data and only writes to the disk when the buffer is full. Here is an example that uses BufferedOutputStream with default buffer size to write data to a binary file:
try // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); BufferedOutputStream writer = new BufferedOutputStream(fos); // write data to file writer.write("Hey, there!".getBytes()); writer.write("\n".getBytes()); writer.write("How are you doing?".getBytes()); // flush remaining bytes writer.flush(); // close the writer writer.close(); > catch (IOException ex) ex.printStackTrace(); >
Notice the writer.flush() method call in the above code. You must call this method before closing the BufferedOutputStream instance to make sure that the remaining data in the internal buffer is flushed to the disk. You can also specify a custom internal buffer size like below:
// custom buffer size int BUFFER_SIZE = 16 * 1024; // 16KB // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); BufferedOutputStream writer = new BufferedOutputStream(fos, BUFFER_SIZE);
If you are writing a binary file with an encoding other than the default character encoding of the operating system or if you want to write non-ASCII characters, you should the OutputStreamWriter class as shown below:
try // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); // set encoding to UTF_8 OutputStreamWriter writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8); // write data to file writer.write("Hey, there!"); writer.write("\n"); writer.write("How are you doing?"); // flush remaining bytes writer.flush(); // close the writer writer.close(); > catch (IOException ex) ex.printStackTrace(); >
You can even wrap the OutputStreamWriter object in a BufferedWriter object to improve the performance by reducing the number of I/O operations performed:
try // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); // set encoding to UTF_8 OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); // wrap in `BufferedWriter` BufferedWriter writer = new BufferedWriter(osw); // write data to file writer.write("Hey, there!"); writer.newLine(); writer.write("How are you doing?"); // flush remaining bytes writer.flush(); // close the writer writer.close(); > catch (IOException ex) ex.printStackTrace(); >
For more file read and write examples, check out the Reading and Writing Files in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.