Saturday, July 31, 2021

Java decimal to binary

To convert decimal to binary,

1. Divide the number by 2.

2. Get the remainder and put in string builder object

3. Take the quotient for next iteration.

4. Repeat the process while quotient  >=1

5. Reverse the string builder data, result will be binary representation of decimal

 public class DecimToBinary {

public static void main(String[] args) {

int data = 20;

StringBuilder builder = new StringBuilder();

while (data >= 1) {

builder.append(data % 2);

data = data / 2;

}

System.out.println(builder.reverse());

}

}

Output : 10100

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home