Android byte array conversion hex string (IoT development Summary)

Source: Internet
Author: User
Tags pow



Think of the outsourced development of the Internet of things in the previous period, often encountering data that is accepted via WiFi, either by converting to a hexadecimal string, or finally by a decimal. are developed on the basis of agreement between the two parties. Then I send the past data also need, after a special conversion to byte bytes sent past, hardware side received not garbled data.





1, hardware debugging sent to Android this is hex dataraw data: A. 59 45 2 (0C 3B)---------------- 3. FD 16 CS

Android read data is a byte byte array


DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte readBuffer[] = new byte[64];	
int count = 0;
 try {
	count = dis.read(readBuffer);
      } catch (IOException e) {
	continue;
      } 


Readbuffer received data such as: 104, 56, 56, 104, 0, 114, 120, 85, 52, 18, 67, 35, 1, 7, 0, 0, 0, 0, 12, 19, 120, 86, 52, 18, 12, 59, 1 20, 52, 18, 12, 38, 120, 86, 52, 18, 11, 89, 69, 35, 0, 2,-3, 23, 0, 0, 22





Then to convert this data into a 16 binary string, if you switch directly to string string that must be garbled. Because hardware debugging is sent to Android this is hex data.



Readbuffer byte array after the data hexadecimal is like this: a.------------------------------0C, XX, xx, XX, 17, 0C, 3B,, 00, 0C, +, +,------------------- , 00, 16
You can see that the hardware is not the same as the hair. This is not hexadecimal y,cs is filled with 00.
Of course, these are based on the two sides to send and receive data to resolve, processing.





2, the Android side sent to the hardware sideThe raw data for Android is this: A0 16, also a hexadecimal string
All you need to do is convert the hexadecimal string into a byte array.
Conversion code:
Private String mstrRestartSend = "FE FE 68 04 04 68 53 FD 50 00 A0 16";
         Private byte[] mRestart = null;
         mRestart = StringUtil.HexCommandtoByte(mstrRestartSend.getBytes());

Public class StringUtil {
     // Convert hexadecimal string to byte array
Public static byte[] HexCommandtoByte(byte[] data) {
If (data == null) {
Return null;
}
Int nLength = data.length;

String strTemString = new String(data, 0, nLength);
String[] strings = strTemString.split(" ");
nLength = strings.length;
Data = new byte[nLength];
For (int i = 0; i < nLength; i++) {
If (strings[i].length() != 2) {
Data[i] = 00;
Continue;
}
Try {
Data[i] = (byte)Integer.parseInt(strings[i], 16);
} catch (Exception e) {
Data[i] = 00;
Continue;
}
}

Return data;
}
   } 
so the past will not be wrong or garbled.
Many beginners, especially in the internet of things, do not understand the conversion of this basic data exchange.


3, wrote the demo test conversion data conversion


: Download
Example diagram:

4, online collection of more comprehensive Java underlying data conversionconversion between binary, decimal, hexadecimal, and ASCII code and string and byte arrays and hexadecimal strings in Java
Public class DigitalTrans {

    /**
     * numeric string to ASCII string
     *
     * @param String
     * string
     * @return ASCII string
     */
    Public static String StringToAsciiString(String content) {
        String result = "";
        Int max = content.length();
        For (int i = 0; i < max; i++) {
            Char c = content.charAt(i);
            String b = Integer.toHexString(c);
            Result = result + b;
        }
        Return result;
    }
    /**
     * hexadecimal to string
     *
     * @param hexString
     * hex string
     * @param encodeType
     * Encoding type 4: Unicode, 2: normal encoding
     * @return string
     */
    Public static String hexStringToString(String hexString, int encodeType) {
        String result = "";
        Int max = hexString.length() / encodeType;
        For (int i = 0; i < max; i++) {
            Char c = (char) DigitalTrans.hexStringToAlgorism(hexString
                    .substring(i * encodeType, (i + 1) * encodeType));
            Result += c;
        }
        Return result;
    }
    /**
     * Hexadecimal string packed in decimal
     *
     * @param hex
     * hex string
     * @return decimal value
     */
    Public static int hexStringToAlgorism(String hex) {
        Hex = hex.toUpperCase();
        Int max = hex.length();
        Int result = 0;
        For (int i = max; i > 0; i--) {
            Char c = hex.charAt(i - 1);
            Int algorism = 0;
            If (c >= '0' && c <= '9') {
                Algorism = c - '0';
            } else {
                Algorism = c - 55;
            }
            Result += Math.pow(16, max - i) * algorism;
        }
        Return result;
    }
    /**
     * Sixteen to binary
     *
     * @param hex
     * hex string
     * @return binary string
     */
    Public static String hexStringToBinary(String hex) {
        Hex = hex.toUpperCase();
        String result = "";
        Int max = hex.length();
        For (int i = 0; i < max; i++) {
            Char c = hex.charAt(i);
            Switch (c) {
            Case '0':
                Result += "0000";
                Break;
            Case '1':
                Result += "0001";
                Break;
            Case '2':
                Result += "0010";
                Break;
            Case '3':
                Result += "0011";
                Break;
            Case '4':
                Result += "0100";
                Break;
            Case '5':
                Result += "0101";
                Break;
            Case '6':
                Result += "0110";
                Break;
            Case '7':
                Result += "0111";
                Break;
            Case '8':
                Result += "1000";
                Break;
            Case '9':
                Result += "1001";
                Break;
            Case 'A':
                Result += "1010";
                Break;
            Case 'B':
                Result += "1011";
                Break;
            Case 'C':
                Result += "1100";
                Break;
            Case 'D':
                Result += "1101";
                Break;
            Case 'E':
                Result += "1110";
                Break;
            Case 'F':
                Result += "1111";
                Break;
            }
        }
        Return result;
    }
    /**
     * ASCII string to numeric string
     *
     * @param String
     * ASCII string
     * @return string
     */
    Public static String AsciiStringToString(String content) {
        String result = "";
        Int length = content.length() / 2;
        For (int i = 0; i < length; i++) {
            String c = content.substring(i * 2, i * 2 + 2);
            Int a = hexStringToAlgorism(c);
            Char b = (char) a;
            String d = String.valueOf(b);
            Result += d;
        }
        Return result;
    }
    /**
     * Convert decimal to a hex string of the specified length
     *
     * @param algorism
     * int decimal number
     * @param maxLength
     * int converted hexadecimal string length
     * @return String Converted hex string
     */
    Public static String algorismToHEXString(int algorism, int maxLength) {
        String result = "";
        Result = Integer.toHexString(algorism);

        If (result.length() % 2 == 1) {
            Result = "0" + result;
        }
        Return patchHexString(result.toUpperCase(), maxLength);
    }
    /**
     * Byte array is converted to ordinary string (ASCII corresponding character)
     *
     * @param bytearray
     * byte[]
     * @return String
     */
    Public static String bytetoString(byte[] bytearray) {
        String result = "";
        Char temp;

        Int length = bytearray.length;
        For (int i = 0; i < length; i++) {
            Temp = (char) bytearray[i];
            Result += temp;
        }
        Return result;
    }
    /**
     * Binary string to decimal
     *
     * @param binary
     * binary string
     * @return decimal value
     */
    Public static int binaryToAlgorism(String binary) {
        Int max = binary.length();
        Int result =
0;
        For (int i = max; i > 0; i--) {
            Char c = binary.charAt(i - 1);
            Int algorism = c - '0';
            Result += Math.pow(2, max - i) * algorism;
        }
        Return result;
    }

    /**
     * Decimal conversion to hexadecimal string
     *
     * @param algorism
     * int decimal number
     * @return String The corresponding hex string
     */
    Public static String algorismToHEXString(int algorism) {
        String result = "";
        Result = Integer.toHexString(algorism);

        If (result.length() % 2 == 1) {
            Result = "0" + result;

        }
        Result = result.toUpperCase();

        Return result;
    }
    /**
     * The HEX string is prepended with 0, which is mainly used for insufficient length digits.
     *
     * @param str
     * String hex string that needs to be replenished
     * @param maxLength
     * int length of the hex string after supplementation
     * @return Supplementary results
     */
    Static public String patchHexString(String str, int maxLength) {
        String temp = "";
        For (int i = 0; i < maxLength - str.length(); i++) {
            Temp = "0" + temp;
        }
        Str = (temp + str).substring(0, maxLength);
        Return str;
    }
    /**
     * Convert a string to an int
     *
     * @param s
     * String string to be converted
     * @param defaultInt
     * int Default number returned if an exception occurs
     * @param radix
     * int What is the string to be converted, such as 16 8 10.
     * @return int converted number
     */
    Public static int parseToInt(String s, int defaultInt, int radix) {
        Int i = 0;
        Try {
            i = Integer.parseInt(s, radix);
        } catch (NumberFormatException ex) {
            i = defaultInt;
        }
        Return i;
    }
    /**
     * Convert a numeric string in decimal form to int
     *
     * @param s
     * String string to be converted
     * @param defaultInt
     * int Default number returned if an exception occurs
     * @return int converted number
     */
    Public static int parseToInt(String s, int defaultInt) {
        Int i = 0;
        Try {
            i = Integer.parseInt(s);
        } catch (NumberFormatException ex) {
            i = defaultInt;
        }
        Return i;
    }
    /**
     * Convert hexadecimal string to Byte array, convert each hexadecimal character to a Byte
     *
     * @param hex
     * hex string
     * @return byte conversion result
     */
    Public static byte[] hexStringToByte(String hex) {
        Int max = hex.length() / 2;
        Byte[] bytes = new byte[max];
        String binarys = DigitalTrans.hexStringToBinary(hex);
        For (int i = 0; i < max; i++) {
            Bytes[i] = (byte) DigitalTrans.binaryToAlgorism(binarys.substring(
                    i * 8 + 1, (i + 1) * 8));
            If (binarys.charAt(8 * i) == '1') {
                Bytes[i] = (byte) (0 - bytes[i]);
            }
        }
        Return bytes;
    }
    /**
     * Convert hex string to byte array
     *
     * @return the array of byte
     */
    Public static final byte[] hex2byte(String hex)
            Throws IllegalArgumentException {
        If (hex.length() % 2 != 0) {
            Throw new IllegalArgumentException();
        }
        Char[] arr = hex.toCharArray();
        Byte[] b = new byte[hex.length() / 2];
        For (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            Int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        Return b;
    }
    /**
     * Convert byte array to hex string
     *
     * @param b
     * byte[] byte array to be converted
     * @return String hex string
     */
    Public static final String byte2hex(byte b[]) {
        If (b == null) {
            Throw new IllegalArgumentException(
                    "Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        For (int n = 0; n < b.length; n++) {
            Stmp = Integer.toHexString(b[n] & 0xff);
            If (stmp.length() == 1) {
                Hs = hs + "0" + stmp;
            } else {
                Hs = hs + stmp;
            }
        }
        Return hs.toUpperCase();
    }
}  

Android byte array conversion hex string (IoT development Summary)


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.