zoukankan      html  css  js  c++  java
  • 16进制转换字节数组工具类

    public class StringUtil {
    	public static String str = "696d706f7274";
    
    	public static void main(String[] args) {
    		System.out.println(new String(getBytes(str)));
    	}
    
    	public static boolean isOdd(String str) {
    		int length = str.length();
    		int isOdd = length % 2;
    		if (isOdd == 0)
    			return false;
    		else
    			return true;
    	}
    
    	public static byte[] getBytes(String str) {
    		boolean isOdd = isOdd(str);
    		int size = str.length();
    		if (isOdd) {
    			byte[] byteOdd = new byte[size / 2 + 1];
    			for (int j = 0, i = 0; i < str.length() - 1; i++) {
    				if (i % 2 == 0) {
    					byte a = getByteFromChar(str.charAt(i));
    					byte b = getByteFromChar(str.charAt(++i));
    					byteOdd[j++] = (byte) (a * 16 + b);
    				}
    
    			}
    			byteOdd[size / 2] = (byte) str.charAt(str.length() - 1);
    			return byteOdd;
    		} else {
    			byte[] byteEven = new byte[size / 2];
    			for (int j = 0, i = 0; i < str.length(); i++) {
    				if (i % 2 == 0) {
    					byte a = getByteFromChar(str.charAt(i));
    					byte b = getByteFromChar(str.charAt(++i));
    					byteEven[j++] = (byte) (a * 16 + b);
    				}
    
    			}
    			return byteEven;
    		}
    
    	}
    
    	public static byte getByteFromChar(char c) {
    		if (c == '0') {
    			return 0;
    		} else if (c == '1') {
    			return 1;
    		} else if (c == '2') {
    			return 2;
    		} else if (c == '3') {
    			return 3;
    		} else if (c == '4') {
    			return 4;
    		} else if (c == '5') {
    			return 5;
    		} else if (c == '6') {
    			return 6;
    		} else if (c == '7') {
    			return 7;
    		} else if (c == '8') {
    			return 8;
    		} else if (c == '9') {
    			return 9;
    		} else if (c == 'a') {
    			return 10;
    		} else if (c == 'b') {
    			return 11;
    		} else if (c == 'c') {
    			return 12;
    		} else if (c == 'd') {
    			return 13;
    		} else if (c == 'e') {
    			return 14;
    		} else if (c == 'f') {
    			return 15;
    		}
    		return -1;
    	}
    
    }
    


  • 相关阅读:
    javaSE基础知识
    oracle错误分析:ora-04063:view view_test has errors
    爬虫—01-爬虫原理与数据抓取
    Web—13-判断网站请求来自手机还是pc浏览器
    Web—12-详解CSS的相对定位和绝对定位
    Web—11-手机端页面适配
    Web—10-前端性能优化
    Web—09-正则表达式
    知识储备—01-进程,线程,多线程相关总结
    Web—08-移动端库和框架
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6748795.html
Copyright © 2011-2022 走看看