Java 16 binary and string Direct conversion creationtime--2018 July 12 09:39 author:marydon1.16 conversion into a string
/*** 16 binary converted directly into string * @explain *@paramhexstr 16 binary String *@returnString*/ Public Staticstring fromhexstring (String hexstring) {//for receiving conversion resultsString result = ""; //Turn CapitalHexString =hexstring.touppercase (); //16 binary charactersString hexdigital = "0123456789ABCDEF"; //Converting a 16 binary string into a char array Char[] Hexs =Hexstring.tochararray (); //Can be divisible by 16, and must be divisible by 2. byte[] bytes =New byte[Hexstring.length ()/2]; intN; for(inti = 0; i < bytes.length; i++) {n= Hexdigital.indexof (hexs[2 * i]) * + hexdigital.indexof (hexs[2 * i + 1)]); Bytes[i]= (byte) (N & 0xFF); } //byte[]-->stringresult =NewString (bytes); returnresult;}
2. String converted to uppercase 16 binary string
/*** String conversion to 16 binary string (uppercase) * @explain because the Java escape string has a special meaning in Java, * So when the string contains an escape string and converts it to 16, a 16 binary is converted into a string, which can cause problems: * JA VA will parse it as the meaning of the escape string.@paramStr string (remove Java escape character) *@return16 binary String *@throwsException*/ Public StaticString tohexstring (String str)throwsException {//for receiving conversion resultsString hexstring = ""; //1. Check if special character content is included//Java Special escape character//string[] Escapearray = {"\b", "\ T", "\ n", "\f", "\ r", "\" "," \ "", "\ \"};String[] Escapearray = {"\b", "\ T", "\ n", "\f", "\ r"}; //used to verify whether the parameter contains special escape characters BooleanFlag =false; //Iteration for(String esacapestr:escapearray) {//One true is true if(Str.contains (ESACAPESTR)) {flag=true; Break;//terminating Loops } } //contains special characters if(flag)Throw NewException ("argument string cannot contain escape characters!) "); //16 binary characters Char[] Hexarray = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '}; StringBuilder SB=NewStringBuilder (); //string-->byte[] byte[] bs =str.getbytes (); intbit; for(inti = 0; i < bs.length; i++) {bit= (Bs[i] & 0x0f0) >> 4; Sb.append (Hexarray[bit]); Bit= Bs[i] & 0x0f; Sb.append (Hexarray[bit]); } hexstring=sb.tostring (); returnhexstring;}
3. Testing
/**@param @throws Exception */public staticvoidthrows Exception { // where, \ ' \ ' \ \ \ Actual string represents: ' "\ String str = "Zhang San &$ John Doe ((,,//\ ' \" \ \ "" "" +-*/!!~. =--??; ; "; = tohexstring (str); System.out.println (HEXSTR); System.out.println (fromhexstring (HEXSTR));}
Related recommendations:
- Conversion between Java byte array and 16 binary
- The Java byte array and string are transferred to each other
Java 16 binary and string conversion directly to each other