...
|
...
|
@@ -43,6 +43,8 @@ public class ByteUtils { |
43
|
43
|
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
|
44
|
44
|
|
45
|
45
|
public static final String UTF_8 = "UTF-8";
|
|
46
|
+
|
|
47
|
+ private static String hexString="0123456789ABCDEF";
|
46
|
48
|
/**
|
47
|
49
|
* 将short整型数值转换为字节数组
|
48
|
50
|
*
|
...
|
...
|
@@ -785,4 +787,64 @@ public class ByteUtils { |
785
|
787
|
int highByte = (src & 0x00FF) << 8;
|
786
|
788
|
return lowByte | highByte;
|
787
|
789
|
}
|
|
790
|
+
|
|
791
|
+ /**
|
|
792
|
+ * 将字符串编码成16进制数字,适用于所有字符(包括中文)
|
|
793
|
+ * @param str 字符串
|
|
794
|
+ * @return
|
|
795
|
+ */
|
|
796
|
+ public static String stringEncodeToHex(String str) {
|
|
797
|
+ //根据默认编码获取字节数组
|
|
798
|
+ byte[] bytes=str.getBytes();
|
|
799
|
+ StringBuilder sb=new StringBuilder(bytes.length*2);
|
|
800
|
+ //将字节数组中每个字节拆解成2位16进制整数
|
|
801
|
+ for(int i=0;i<bytes.length;i++)
|
|
802
|
+ {
|
|
803
|
+ sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
|
|
804
|
+ sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
|
|
805
|
+ }
|
|
806
|
+ return sb.toString();
|
|
807
|
+
|
|
808
|
+ }
|
|
809
|
+
|
|
810
|
+ /**
|
|
811
|
+ * 将16进制数字解码成字符串,适用于所有字符(包括中文)
|
|
812
|
+ * @param hex 16进制
|
|
813
|
+ * @return
|
|
814
|
+ */
|
|
815
|
+ public static String hexDecodeToString(String hex) {
|
|
816
|
+ try{
|
|
817
|
+ byte[] baKeyword = new byte[hex.length()/2];
|
|
818
|
+ for(int i = 0; i < baKeyword.length; i++) {
|
|
819
|
+ baKeyword[i] = (byte)(0xff & Integer.parseInt(hex.substring(i*2, i*2+2),16));
|
|
820
|
+ }
|
|
821
|
+ return new String(baKeyword,"UTF-8");
|
|
822
|
+ }catch (UnsupportedEncodingException e){
|
|
823
|
+ return null;
|
|
824
|
+ }
|
|
825
|
+ }
|
|
826
|
+
|
|
827
|
+ public static byte[] hexToByteArray(String inHex){
|
|
828
|
+ inHex.replace(" ","");
|
|
829
|
+ int hexlen = inHex.length();
|
|
830
|
+ byte[] result;
|
|
831
|
+ if (hexlen % 2 == 1){
|
|
832
|
+ //奇数
|
|
833
|
+ hexlen++;
|
|
834
|
+ result = new byte[(hexlen/2)];
|
|
835
|
+ inHex="0"+inHex;
|
|
836
|
+ }else {
|
|
837
|
+ //偶数
|
|
838
|
+ result = new byte[(hexlen/2)];
|
|
839
|
+ }
|
|
840
|
+ int j=0;
|
|
841
|
+ for (int i = 0; i < hexlen; i+=2){
|
|
842
|
+ result[j]=hexToByte(inHex.substring(i,i+2));
|
|
843
|
+ j++;
|
|
844
|
+ }
|
|
845
|
+ return result;
|
|
846
|
+ }
|
|
847
|
+ public static byte hexToByte(String inHex){
|
|
848
|
+ return (byte)Integer.parseInt(inHex,16);
|
|
849
|
+ }
|
788
|
850
|
} |
...
|
...
|
|