字符转换工具类

本文介绍了一个实用工具类,用于处理IP地址和URL的各种操作,包括IP地址转换为字符串、验证IP地址格式、解析URL获取主机名和端口、转换路径等。这些工具方法对于网络编程和Web开发十分有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Utils {


/**
* IpAddress 转成String
* @param i
* @return
*/
public static String intToString(int i) {
return ((i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + ((i >> 24) & 0xFF));
}

public static boolean ipIsExact(String ip) {
Pattern pattern = Pattern
.compile("^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$");
return pattern.matcher(ip).matches();
}

/**
* url转成String
* @param url
* @return
*/
public static String[] urlToString(String url){
String[] result=url.split("//");
String[] str=result[1].split(":");
System.err.println(str[0]);
System.err.println(str[1]);
return str;
}

/**
* 将路径转换成 可用路径
* @param path
* @return
*/
public static String matchPath(String path){
if(path.startsWith("/")){
return path.substring(1, path.length());
}
return path;
}

public static int bytesToInt(byte[] intByte) {   
int fromByte = 0;
for (int i = 0; i < 2; i++) {
int n = (intByte[i] < 0 ? (int) intByte[i] + 256 : (int) intByte[i]) << (8 * (i - 1));
fromByte += n;
}
return fromByte;
}

public static long StringToLong(String str){
long result = Long.valueOf(str, 16);
return result;
}

public static String getStringLengisEight(String str){
String result = str;
for (int i = str.length(); i < 8; i++) {
result = "0" + result;
}
if (result.length() > 8) {
result = result.substring(result.length() - 8);
}
result = result.toUpperCase();
return result;
}

public static String bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}

public static long bytes2Long(byte[] b){
String str = bytes2HexString(b);
return Long.valueOf(str, 16);
}

public static int bytes2Int(byte[] b){
String str = bytes2HexString(b);
return Integer.valueOf(str, 16);
}

//把8位16进制字符串转为整数
public static int tranferHexStringToInt(String hex){
long l1=Long.parseLong(hex, 16);
if(l1>0x7fffffff){
l1=l1-0x7fffffff;
}
return (int)l1;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值