Java hexadecimal string-hexstring

Source: Internet
Author: User

Java hexadecimal string-hexstring


http://my.oschina.net/xinxingegeya/blog/287476

Byte[] and hexadecimal strings are converted to each other

In Java, Byte uses a binary representation of 8 bits, and we know that each character in the 16 binary needs to be represented by a 4-bit bits.


So we can convert each byte to two corresponding 16 characters, that is, the high 4 and low 4 bits of byte are converted to the corresponding 16-character H and L, and combined to get the result of byte conversion to the 16 binary string.


New String (H) + new String (L).


In the same way, the opposite conversion also converts two 16 characters into a byte, as in the same principle.


Based on the above, we can convert the byte[] array to a 16 binary string, and of course we can convert the 16 binary string to the byte[] array.


Java code:

package test; public class hex {     /**      *  an array of lowercase characters used to build the output of the hexadecimal character      */    private  static final char[] digits_lower = {' 0 ',  ' 1 ',  ' 2 ',  ' 3 ',  ' 4 ',   ' 5 ',             ' 6 ',  ' 7 ',  ' 8 ',   ' 9 ',  ' a ',  ' B ',  ' C ',  ' d ',  ' e ',  ' F '};     /**      *  an array of uppercase characters used to create the output of the hexadecimal character      */     private static final char[] digits_upper = {' 0 ',  ' 1 ',  ' 2 ',  ' 3 ',   ' 4 ',  ' 5 ',             ' 6 ',  ' 7 ',   ' 8 ',  ' 9 ',  ' A ',  ' B ',  ' C ',  ' D ',  ' E ',  ' F '};      /**     *  converts a byte array to a hexadecimal character array      *     *  @param  data  byte[]     *  @return   Hex char[]     */     public static char[] encodehex (Byte[] data)  {         return encodehex (data, true);    }      /**     *  convert a byte array to a hexadecimal character array      *      *  @param  data        byte[]      *  @param  toLowerCase <code>true</code>  Convert to lowercase format  , <code>false</code>  convert to uppercase format      *  @return   Hex char[]     */    public static char[]  Encodehex (byte[] data, boolean&Nbsp;tolowercase)  {        return encodehex (data,  Tolowercase ? digits_lower : digits_upper);    }      /**     *  convert a byte array to a hexadecimal character array      *      *  @param  data     byte[]      *  @param  toDigits  char[]     *  for controlling output @return   hex Char []     */    protected static char[] encodehex ( Byte[] data, char[] todigits)  {        int l  = data.length;        char[] out = new  char[l << 1];        // two characters  Form the hex value.        for  (int i = 0, j = 0;  i < l; i++)  {             out[j++] = todigits[(0xf0 & data[i])  >>> 4];             out[j++] = toDigits[0x0F &  data[i]];        }         return out;    }     /**      *  converts a byte array to a hexadecimal string      *     *  @param  data  byte[]     *  @return   Hex string     */     public static string encodehexstr (Byte[] data)  {         retUrn encodehexstr (data, true);    }     /**      *  convert a byte array to a hexadecimal string      *     * @ param data        byte[]     * @ param tolowercase <code>true</code>  converted to lowercase format  , <code>false</code >  convert to uppercase format      *  @return   Hex string     */     public static string encodehexstr (byte[] data, boolean  toLowerCase)  {        return encodehexstr (data,  Tolowercase ? digits_lower : digits_upper);    }      /**     *  convert a byte array to a hexadecimal string      *      *  @param data     byte[]     *  @param  todigits   char[]     *  @return   hex string     * for controlling output /    protected static string encodehexstr (byte[] data, char[]  todigits)  {        return new string (EncodeHex ( data, todigits));    }     /**      *  converts a hexadecimal character array to a byte array      *     *  @param  data   Hex char[]     *  @return  byte[]     * @ throws runtimeexception  if the source hexadecimal character array is a strange length, the run-time exception will be thrown      */     public static byte[] decodehex (Char[] data)  {          int len = data.length;         if  ((len  &AMP;&NBSP;0X01)  != 0)  {             throw new runtimeexception ("odd number of characters.");         }         byte[]  out = new byte[len >> 1];          // two characters form the hex value.         for  (int i = 0, j = 0; j < len; i++)  {            int f = todigit ( DATA[J],&NBSP;J)  << 4;             j++;            f = f | todigit (DATA[J],&NBSP;J);             j++;             out[i] =  (Byte)   (F&NBSP;&AMP;&NBSP;0XFF);         }         return out;    }      /**     *  convert hexadecimal characters to an integer       *     *  @param  ch     Hex char      *  @param  index  position of hexadecimal characters in a character array      *  @return   An integer      *  @throws  RuntimeException  throws a run-time exception when CH is not a valid hexadecimal character       */    protected static int todigit (Char ch,  int index)  {&nbsP;       int digit = character.digit (ch, 16);         if  (digit == -1)  {             throw new runtimeexception ("Illegal hexadecimal  character  " + ch                     +  " at index "  + index);         }        return digit;     }     public static void main (String[] args)  {        String srcStr =  "Qwer";         string encodestr = encodehexstr (SrcStr.getBytes ());      &nbsP;  string decodestr = new string (Decodehex (Encodestr.tochararray ()));         system.out.println ("Before encode:"  + srcStr);         system.out.println ("After encode:"  + encodeStr);         system.out.println ("Convert:"  + decodestr);     } }


You can also use the common codec to encode hex string, the following code fragment,

@Testpublic  void test ()  {    String hello =  " ASDFASDF you have to ASDFASDFASDFASDFL ";    try {         string hexstring = hex.encodehexstring (Hello.getbytes ("Utf-8"));         string hexstring2 = hex.encodehexstring (Hello.getBytes ("ASCII"));         string hexstring3 = hex.encodehexstring ( Hello.getbytes ("GBK"));         string hexstring4 = new  string (Hex.encodehex (Hello.getbytes ("Utf-8"),  false));         system.out.println (hexstring);         system.out.println ( HEXSTRING2);         system.out.println (HEXSTRING3);         system.out.println (hexstrING4);    } catch  (unsupportedencodingexception e)  {         e.printstacktrace ();     }}


===================================end===================================


Java hexadecimal string-hexstring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.