赞
踩
一、将 "a"转化为 "10" 的样式
- public static String hexStrToIntStr(String hexStr) {
- // 不存在数据时 返回null
- if (hexStr == null || hexStr == "") {
- return null;
- }
- String regexStr = "^[A-Fa-f0-9]+$";
- // 字符串超过十六进制数 返回null
- if (!hexStr.matches(regexStr)) {
- return null;
- }
- // 进行字符的转换
- Integer in = Integer.parseInt(hexStr, 16);
- return String.valueOf(in);
- }
测试代码
- System.out.println(hexStrToIntStr("a"));
- System.out.println(hexStrToIntStr("Aa"));
-
- 10
- 170
二、将 "15" 转化成 "f"的格式
- public static String intStrToHexStr(String intStr) {
- // 不存在数据时 返回null
- if (intStr == null || intStr == "") {
- return null;
- }
- //进行转换操作
- StringBuffer Hex=new StringBuffer("");
- String m="0123456789abcdef";
- int i = Integer.parseInt(intStr, 10);
- if(i==0) Hex.append(i);
- while (i!=0) {
- Hex.append(m.charAt(i%16));
- i>>=4;
- }
- return Hex.reverse().toString();
- }
测试代码
- System.out.println(intStrToHexStr("15"));
- System.out.println(intStrToHexStr("170"));
-
- f
- aa
三、将 "01" 转化为 "0x01" 的样式
- public static byte[] HexString2Bytes(String src) {
- byte[] ret = new byte[src.length() / 2];
- byte[] tmp = src.getBytes();
- for (int i = 0; i < tmp.length / 2; i++) {
- ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
- }
- return ret;
- }
- public static byte uniteBytes(byte src0, byte src1) {
- byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
- .byteValue();
- _b0 = (byte) (_b0 << 4);
- byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
- .byteValue();
- byte ret = (byte) (_b0 ^ _b1);
- return ret;
- }
四、将byte[]{0x01,0x11} 转化为 "0111" 格式输出
- public static String bytesToHexString(byte[] src) {
- StringBuilder stringBuilder = new StringBuilder("");
- if(src == null || src.length <= 0) {
- return null;
- }
- for (int i = 0; i < src.length; i++) {
- int v = src[i] & 0xFF;
- String hv = Integer.toHexString(v);
- if(hv.length() < 2) {
- stringBuilder.append(0);
- }
- stringBuilder.append(hv);
- }
- return stringBuilder.toString();
- }
五、将byte[]{0,0} 转化为 "00"格式输出
- public static String byteArrayToString(byte[] bytes) {
- StringBuilder stringBuilder = new StringBuilder("");
- if(bytes == null || bytes.length <= 0) {
- return null;
- }
- for (int i = 0; i < bytes.length; i++) {
- int v = bytes[i] & 0xFF;
- String hv = Integer.toHexString(v);
- stringBuilder.append(hv);
- }
- return stringBuilder.toString();
- }
六、java正则判断IMEI、MAC、IMSI信息
- public static final String imsiRegex = "^[0-9]{15,16}$";
- public static final String imeiRegex = "^[0-9]{15,17}$";
- public static final String macRegex = "^([A-Fa-f0-9]{2}(-[A-Fa-f0-9]{2}){5})";
-
- /**
- * @param regex
- * 正则表达式字符串
- * @param str
- * 要匹配的字符串
- * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
- */
- public static boolean match(String regex, String str) {
- Pattern pattern = Pattern.compile(regex);
- Matcher matcher = pattern.matcher(str);
- return matcher.matches();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。