Java convert decimal to binary number
Decimal is a base 10 number system that we all familiar with, binary is a base 2 number system that computer understands. Computer programs written in various programming languages are converted into binary through compilers. To convert a decimal to a binary number, we divide the decimal number by 2 and keep the remainder 1 or 0 if there is no remainder until we get to 1 divide by 2 equal to 0 with remainder 1. Put together all the remainder including 0s, from the last remainder 1 to the first remainder, and it is the binary equivalent the decimal number.
For example, convert decimal number 291 to a binary number:
- 291/2=145…1
- 145/2=72….1
- 72/2=36…..0
- 36/2=18…..0
- 18/2=9……0
- 9/2=4…….1
- 4/2=2…….0
- 2/2=1…….0
- 1/2=0…….1
100100011 is the binary equivlent of the decimal number 291.
To convert the binary back to decimal:
- 1*2^0=1
- 1*2^1=2
- 0*2^2=0
- 0*2^3=0
- 0*2^4=0
- 1*2^5=32
- 0*2^6=0
- 0*2^7=0
- 1*2^8=256
1+2+0+0+0+32+0+0+256=291
Here is Java program that converts a given decimal to a binary number.
public class DecimalToBinary { public static String toBinary(int num) { String b=""; int remainder; while(num>0) { remainder = num%2; b = Integer.toString(remainder) + b; num = num / 2; } return b; } public static void main(String args[]) { String bin = DecimalToBinary.toBinary(291); System.out.println(bin); } }
Search within Codexpedia
Search the entire web