华为上机:IP地址转换

时间:2023-03-09 09:30:11
华为上机:IP地址转换
IP地址转换
描述:

IP地址的长度为32,即有2^32-1个地址。IP地址一般采用点分十进制表示法,例如"192.168.1.1"。IP地址也可以直接用一个32位的整数进行表示。本题目要求根据给定的整数IP地址表示发,将其转换为点分十进制的形式。

举个例子:

输入整数IP地址为 3232235777

其对应十六进制为 0xC0A80101

每字节转为十进制 0xC0=192,0xA8=168,0x01=1,0x01=1

则输出为 192.168.1.1

运行时间限制: 1 Sec
内存限制: 100 MByte
输入:

32位正整数IP地址

输出:

点分十进制IP地址

样例输入:
3232235777
样例输出:
192.168.1.1
答案提示:

程序写的有问题,ip对于的整数比较小的适合有错误,100分只得了29分

167773121
10.3.3.193
这个就报错
下面程序是严格一位一位的计算,出错了
import java.util.*;

public class Main6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
Long longA = in.nextLong();
// String hex = longToHex(longA);
String hex = Long.toHexString(longA);
hex = hex.toUpperCase();
String ip = hexToIP(hex);
System.out.println(ip);
} in.close();
}
public static String hexToIP(String hex){
StringBuffer sb = new StringBuffer();
int i;
String s;
for( i=0;i<hex.length()-2;i=i+2){
s = hex.substring(i,i+2);
sb.append(hexToInt(s));
sb.append('.');
}
s = hex.substring(i,i+2);
sb.append(hexToInt(s));
return sb.toString();
}
/**
* 16进制 转化成 10进制
* @param str
* @return
*/
public static int hexToInt(String str){
int res = 0;
int n = str.length();
int pow = (int)Math.pow(16, n-1);
for(int i=0;i<n;i++){
char ch = str.charAt(i);
if(ch<='9'){
res += (ch-48)*pow;
}else{
res += (ch-'A'+10)*pow;
}
pow/=16;
}
return res;
}
/**
* 十进制转化成十六进制
* @param x
* @return
*/
public static String longToHex(long x){
String[] a = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E"};
StringBuffer sb = new StringBuffer();
while(x>0){
int id = (int)(x%16); //求余数,对于数组id
sb.insert(0, a[id]); // 插入到第0个位置
x=x/16; // 更新 }
// sb.insert(0, "0x"); return sb.toString();
}
}

百度一下

通过位运算比较简单了,但是违背了题意思

    public static String bugs(long temp){
long a=((temp&0xff000000)>>24);
long b=((temp&0x00ff0000)>>16);
long c=((temp&0x0000ff00)>>8);
long d=(temp&0x000000ff);
return a+"."+b+"."+c+"."+d;
}