答:参考代码:public static String ipYuMsk(InetAddress ip)
{
byte[] b=ip.getAddress();
long l= b[0]<<24L & 0xff000000L|
b[1]<<16L & 0xff0000L |
b[2]<<8L & 0xff00L |
b[3]<<0L & 0xffL ;
return Integer.toBinaryString((int)l);
}使用:
System.out.println("159.226.178.0=>"+ipYuMsk(InetAddress.getByName("("159.226.178.0")));
运行结果:
159.226.178.0=>10011111111000101011001000000000
{
byte[] b=ip.getAddress();
long l= b[0]<<24L & 0xff000000L|
b[1]<<16L & 0xff0000L |
b[2]<<8L & 0xff00L |
b[3]<<0L & 0xffL ;
return Integer.toBinaryString((int)l);
}使用:
System.out.println("159.226.178.0=>"+ipYuMsk(InetAddress.getByName("("159.226.178.0")));
运行结果:
159.226.178.0=>10011111111000101011001000000000
/**
* @author zzw
* @param a: the basis string
* @param b: the loop string
* @param c: the loop times
* @since 20080527
**/
public static String times(String a,String b,int c){
StringBuilder str = new StringBuilder();
for(int i=0;i<c;i++){
str.append(b);
}
str.append(a);
return str.toString();
}
public static void main(String[] args) {
String ip = "159.2.178.8";
System.out.println(ip);
String[] ipArray = ip.split("[.]");
StringBuilder result = new StringBuilder();
for(int i=0;i<ipArray.length;i++){
String str = Integer.toBinaryString(Integer.parseInt(ipArray[i]));
int length = str.length();
System.out.println(length == 8?str:times(str,"0",8-length));
result.append(length == 8?str:times(str,"0",8-length));
}
System.out.println("result is "+result.toString());
}}