Java基本类型转换大全(字符串、字节数组、Hex、Base64)

一、字符串 >> 字节数组

String s1 = "hello world";
byte[] b1 = s1.getBytes();
System.out.println(Arrays.toString(b1));

二、字节数组 >> 字符串

byte[] b1 = {
    
    104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100};
String s1 = new String(b1);
System.out.println(s1);

三、Hex >> 字节数组

public static byte hexToByte(String inHex){
    
    
        return (byte)Integer.parseInt(inHex,16);
    }

    public static byte[] hexToByteArray(String inHex){
    
    
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
    
    
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
    
    
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
    
    
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;
    }

四、字节数组 >> Hex

public static String byteToHex(byte b)
    {
    
    
        String hexString = Integer.toHexString(b & 0xFF);
        if (hexString.length() < 2)
        {
    
    
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }
    public static String bytesToHex(byte[] bytes)
    {
    
    
        StringBuffer sb = new StringBuffer();
        if (bytes != null && bytes.length > 0)
        {
    
    
            for (int i = 0; i < bytes.length; i++) {
    
    
                String hex = byteToHex(bytes[i]);
                sb.append(hex);
            }
        }
        return sb.toString();
    }

五、Base64 >> Hex

public static String byteToHex(byte b)
    {
    
    
        String hexString = Integer.toHexString(b & 0xFF);
        //由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
        //假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
        if (hexString.length() < 2)
        {
    
    
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }
    public static String bytesToHex(byte[] bytes)
    {
    
    
        StringBuffer sb = new StringBuffer();
        if (bytes != null && bytes.length > 0)
        {
    
    
            for (int i = 0; i < bytes.length; i++) {
    
    
                String hex = byteToHex(bytes[i]);
                sb.append(hex);
            }
        }
        return sb.toString();
    }
    public static String base64Tohex(String bstxt){
    
    
        byte[] bs = Base64.decode(bstxt);
        String hex = bytesToHex(bs);
        return hex.toLowerCase();

    }

猜你喜欢

转载自blog.csdn.net/weixin_51111267/article/details/131805989