Java 字符串與byte之間的相互轉換


 

  • 原理
    我們都知道,在Java里byte類型是占用1個字節,即8位的,而16進制的字符占用4位,所以每個byte可以用兩個字符來表示,反之亦然。

  • 舉個栗子

byte = 123
用二進制表示:0111 1011
每4位用字符表示: 7 b

 

注意:java是用補碼來進行二進制計算的(計算機都用補碼計算),因為上面最高位為0,即為正數,而正數的補碼為自身,所以沒什么問題,

下面看看負數的栗子:

 

16位進制字符串表示: a b
用二進制表示:1010 1011
二進制補碼: 1101 0101
byte:-85 (如果不用補碼計算,應該為171,超出byte的范圍了)

 

是的,原理就這么簡單,接下來用代碼實現:

  • byte[] 轉16進制字符串

 

 

法1
思路:先把byte[] 轉換為char[],再把char[] 轉換為字符串

    public static String bytes2Hex(byte[] src) {
        if (src == null || src.length <= 0) {   
            return null;   
        } 
        
        char[] res = new char[src.length * 2]; // 每個byte對應兩個字符
        final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        for (int i = 0, j = 0; i < src.length; i++) {
            res[j++] = hexDigits[src[i] >> 4 & 0x0f]; // 先存byte的高4位
            res[j++] = hexDigits[src[i] & 0x0f]; // 再存byte的低4位
        }

        return new String(res);
    }

 

法2
思路:先把byte轉換為int類型,再轉換為字符串

    public static String bytes2Hex(byte[] src){   
        if (src == null || src.length <= 0) {   
            return null;   
        } 
        
        StringBuilder stringBuilder = new StringBuilder("");         
        for (int i = 0; i < src.length; i++) {   
            // 之所以用byte和0xff相與,是因為int是32位,與0xff相與后就舍棄前面的24位,只保留后8位
            String str = Integer.toHexString(src[i] & 0xff); 
            if (str.length() < 2) { // 不足兩位要補0
                stringBuilder.append(0);   
            }   
            stringBuilder.append(str);   
        }   
        return stringBuilder.toString();   
    } 

 

 

  • 16進制字符串轉byte[]

思路:先把字符串轉換為char[],再轉換為byte[]。
因為兩個字符對應一個byte,所以字符串的長度不能為奇數喔(哪位有想到好辦法解決這一問題的,求告知)。


    public static byte[] hex2Bytes(String hexString) {   
        if (hexString == null || hexString.equals("")) {   
            return null;   
        }   

        int length = hexString.length() / 2;   
        char[] hexChars = hexString.toCharArray();   
        byte[] bytes = new byte[length];   
        String hexDigits = "0123456789abcdef";
        for (int i = 0; i < length; i++) {   
            int pos = i * 2; // 兩個字符對應一個byte
            int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
            int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
            if(h == -1 || l == -1) { // 非16進制字符
                return null;
            }
            bytes[i] = (byte) (h | l);   
        }   
        return bytes;   
    }

注:注1得到xxxx0000,注2得到0000xxxx,相或就把兩個字符轉換為一個byte了。

 

 

 

  • 再舉個栗子

md5加密

    public static String getMd5ByFile(File file) {
        String ret= null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) > 0) {
                md.update(buffer, 0, len);
            }
            ret = bytes2Hex(md.digest()); // 把md5加密后的byte[]轉換為字符串
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return ret;
    }

 


byte和int互轉 : https://www.cnblogs.com/fps2tao/p/13364487.html

 

 

 

 

 

 

轉 : https://www.jianshu.com/p/a356be438dad

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM