Friday, April 27, 2018

Convert a Decimal Number into Binary Representation

This is very easy to implement.

Principle to Convert

A decimal number is converted into binary number by repeatedly dividing the number by 2 and prepending the remainder. So the first remainder is placed at Unit Place, Second remainder at Tens Place, Third remainder at Hundreds Place and so on.
/**
* Converts given Decimal number into Binary representation
* @param m decimal number to converto to binary
* @return Binary representation of input decimal number
*/
public String convert(int m) {
String binary = "";
while(m > 0) {
binary = (m % 2) + binary; // append new remainder at the beginning
m /= 2;
}
return binary;
} // convert







No comments:

Post a Comment