finished util: StringHelper

This commit is contained in:
free will committed 2021-03-18 19:26:33 +08:00
1 parent 8cf6ed24c9
commit 96650c8f42
2 files changed
+82 -2

No files matched your search

+11
View File
@@ -53,6 +53,12 @@ public class ByteHelper {
// System.arraycopy(buffer,startInt,firstbyte,0,firstbyte.length);
// return firstbyte[0];
}
public static byte getFirstByte(byte[] buffer, int startInt) throws ByteHelperException {
if(startInt >= buffer.length || startInt < 0){
throw new ByteHelperException("buffer out of bounds");
}
return buffer[startInt];
}
/**
* 从byte[]数组指定开始位置获取长度为len的字节数组
@@ -93,6 +99,11 @@ public class ByteHelper {
System.arraycopy(buffer,startInt,lenbytes,0,len);
return lenbytes;
}
public static byte[] getLenBytes(byte[] buffer, int startInt,int len){
byte[] lenbytes=new byte[len];
System.arraycopy(buffer,startInt,lenbytes,0,len);
return lenbytes;
}
/**
* 无符号int转byte[]
+71 -2
View File
@@ -1,5 +1,10 @@
package util;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
/*
* @Author: Wang Feng
* @Description:
@@ -7,8 +12,27 @@ package util;
* @Date: 11:27 2021/3/10
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
*/
public class StringHelper {
private static byte toHexChar(byte n){
return (byte) "0123456789ABCDEF".toCharArray()[n&0xf];
}
private static byte fromHexToChar(byte c){
byte res;
if((c>='0') && (c<='9')){
res= (byte) (c-'0');
}else if((c>='a') && (c<='f')){
res= (byte) (c-'a'+10);
}else if((c>='A') && (c<='F')){
res= (byte) (c-'A'+10);
}else {
res=100;
}
return res;
}
/**
* 对字符串实施百分号编码
* // @Description:
@@ -24,7 +48,28 @@ public class StringHelper {
* @return
*/
public static String escape(String str){
return "";
byte[] strBytes=str.getBytes(StandardCharsets.UTF_8);
int len=strBytes.length;
ByteBuffer byteBuffer = null;
int index=0;
for(int i=0;i<len;i++){
byte ch=strBytes[i];
if((ch>='a'&&ch<='z')||
(ch>='A'&&ch<='Z')||
(ch>='0'&&ch<='9')||
ch=='-'||ch=='.'||ch=='_'||ch=='~'){
byteBuffer.put(index,ch);
index++;
}else{
byteBuffer.put(index,(byte)'%');
index++;
byteBuffer.put(index,toHexChar((byte) ((ch & 0xf0) >> 4)));
index++;
byteBuffer.put(index,toHexChar((byte) (ch & 0xf)));
index++;
}
}
return new String(byteBuffer.array());
}
/**
@@ -33,7 +78,31 @@ public class StringHelper {
* @return
*/
public static String unescape(String str){
return "";
byte[] strBytes=str.getBytes(StandardCharsets.UTF_8);
int len=strBytes.length;
byte[] resBytes=new byte[len];
int index=0;
for (int i = 0; i < len; i++) {
byte ch=strBytes[i];
if((ch=='%')&&(i+2<len)){
byte high=fromHexToChar(strBytes[i+1]);
byte low=fromHexToChar(strBytes[i+2]);
// 如果是无效的hex字符,则保持原样输出
if((high==100)||(low==100)){
resBytes[index]=ch;
index++;
}else {
resBytes[index]= (byte) ((high << 4) | low);
index++;
}
i+=2;
}else{
resBytes[index]=ch;
index++;
}
}
return new String(ByteHelper.getLenBytes(resBytes,0,index));
}