Conversion of a 16 binary value string to a byte array

Source: Internet
Author: User


/**
* Convert a byte array to a string representing 16 binary values, such as: byte[]{8,18} to: 0813, and public static byte[]
* Hexstr2bytearr (String strin) mutually reversible conversion process
*
* @param ARRB
* Byte array to convert
* @return The converted String
* @throws Exception
* This method does not handle any exceptions, all exceptions are thrown
*/
public static String Bytearr2hexstr (byte[] arrb) throws Exception {
int ilen = Arrb.length;
Each byte is represented by two characters, so the length of the string is twice times the length of the array
StringBuffer sb = new StringBuffer (Ilen * 2);
for (int i = 0; i < Ilen; i++) {
int inttmp = Arrb[i];
Convert negative numbers to positive numbers
while (Inttmp < 0) {
inttmp = inttmp + 256;
}
Numbers less than 0F need to be preceded by 0
if (Inttmp < 16) {
Sb.append ("0");
}
Sb.append (Integer.tostring (inttmp, 16));
}
return sb.tostring ();
}

/**
* Converts a String representing 16 binary values to a byte array, and public static string Bytearr2hexstr (byte[] arrb)
* Reciprocal Reversible conversion process
*
* @param strin
* Strings that need to be converted
* @return converted byte array
* @throws Exception
* This method does not handle any exceptions, all exceptions are thrown
*/
public static byte[] Hexstr2bytearr (String strin) throws Exception {
byte[] Arrb = Strin.getbytes ();
int ilen = Arrb.length;

Two characters represent one byte, so the length of the byte array is the length of the string divided by 2
byte[] Arrout = new BYTE[ILEN/2];
for (int i = 0; i < ilen; i = i + 2) {
String strtmp = new String (ARRB, I, 2);
ARROUT[I/2] = (byte) integer.parseint (strtmp, 16);
}
return arrout;
}

Conversion of a 16 binary value string to a byte array

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.