byte [] array with conversion of 16 hexadecimal string

1. The byte [] array is converted into hexadecimal characters.

 / ** 
     * the byte [] array is converted into a hexadecimal character. Generating a two byte character length corresponds. 1: 2 
     * @param bytes, the input byte [] array 
     * @return 16 hexadecimal characters
      * / 
    public  static String byte2Hex ( byte [] bytes) {
         IF (bytes == null ) {
             return  null ; 
        } 
        the StringBuilder Builder = new new the StringBuilder ();
         // iterate byte [] array, converting each byte into a number hexadecimal characters, then spliced together into a string 
        for ( int I = 0; I <bytes.length ; I ++ ) {
             //When converting each byte into a 16 hexadecimal characters, bytes [i] & 0xff if the high bits are 0, the output will be removed, so + 0x100 (plus 1 bit higher), the two characters then taken 
            builder.append (Integer. toString ((bytes [I] & 0xFF) + 0x100, 16) .substring (. 1 )); 
        } 
        return builder.toString (); 
    }

2. Convert the hexadecimal characters into byte [] array

/ ** 
     * converted into a hexadecimal character byte [] array. Contrary to byte2Hex function. 
     * @Param String 16 hexadecimal string 
     * @return byte [] array
      * / 
    public  static  byte [] hex2Byte (String String) {
         IF (String == null || String.length () <. 1 ) {
             return  null ; 
        } 
        // because generating a two byte character, a length corresponding to 1: 2, the byte [] array length is half the length of the string 
        byte [] bytes = new new  byte [String.length () / 2 ];
         // traverse byte [] array, the number of traverse half the length of the string 
        for ( int0 = I; I <String.length () / 2; I ++ ) {
             // taken not two previous character which was converted int, 
            int High = the Integer.parseInt (String.substring (I * 2, I * 2 + 1), 16 );
             // taken not after a two-character, which is converted int, 
            int Low = the Integer.parseInt (String.substring (I * 2 + 1, I + 2 * 2), 16 );
             // high values corresponding to the character * 16 + int int value low, and strong to turn into a byte value
             // such dd, low high 13 * 16 + 13 = 221 (strong converted into byte binary 11011101, corresponding to decimal -35) 
            bytes [I] = ( byte ) (* 16 + High Low); 
        } 
        return bytes; 
    }

Guess you like

Origin www.cnblogs.com/hello4world/p/12147537.html