Write a program to convert Dotted Decimal Notation to binary Notation in java
Code:
import java.util.*;
class Test{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.println("Enter Dotted decimal Notation:");
String dec = scn.next();
int logic = 0;
String res = "";
String[] arr = dec.split("[.]",0);
for(int i=0;i<arr.length;i++){
int num = Integer.parseInt(arr[i]);
if(num> 255){
System.out.println("Invalid dotted decimal Notation");
logic = 1;
break;
}
String bin = toBin(num);
res = res + bin;
}
if(logic == 0){
System.out.println("Binary Notation "+res);
}
}
public static String toBin(int n){
String bin = Integer.toBinaryString(n);
int len = bin.length();
if(bin.length() < 8){
for(int i=0;i<8-len;i++){
bin = "0"+bin;
}
}
return bin;
}
}
o/p::
Comments
Post a Comment