C # 16 conversions between strings and byte arrays

Source: Internet
Author: User

C # 16 conversions between strings and byte arrays
1How to convert a decimal number string into a hexadecimal number string in C #//Decimal Turn binaryConsole.WriteLine ("Binary representation of decimal 166:"+convert.tostring (166,2));//Decimal Turn octalConsole.WriteLine ("octal in decimal 166 indicates:"+convert.tostring (166,8));//Decimal Turn hexConsole.WriteLine ("the hexadecimal representation of decimal 166:"+convert.tostring (166, -)); //Binary goto DecimalConsole.WriteLine ("decimal representation of binary 111101:"+convert.toint32 ("111101",2));//Octal goto DecimalConsole.WriteLine ("the decimal representation of octal 44:"+convert.toint32 (" -",8));//Hexadecimal goto DecimalConsole.WriteLine ("the decimal representation of the hexadecimal cc:"+convert.toint32 ("CC", -));2in the serial communication process, the conversion between the 16 binary and the string and byte array is often used.//Private stringStringtohexstring (strings,encoding encode) {            byte[] b = encode. GetBytes (s);//encodes a string into a byte array according to the specified encoding            stringresult =string.            Empty;  for(inti =0; i < b.length; i++)//byte to 16 characters, separated by%{result+="%"+convert.tostring (B[i], -); }            returnresult; }        Private stringHexstringtostring (stringHS, Encoding encode) {            //split the string with% and remove the null character            string[] chars = hs. Split (New Char[]{'%'},stringsplitoptions.removeemptyentries); byte[] B =New byte[chars.            Length]; //Character-by- byte changes into 16 bytes of data             for(inti =0; I < chars. Length; i++) {B[i]= Convert.tobyte (Chars[i], -); }            //converts a byte array into a string by the specified encoding            returnencode.        GetString (b); }         /// <summary>        ///string to 16 binary byte array/// </summary>       /// <param name= "hexstring" ></param>        /// <returns></returns>        Private Static byte[] Strtotohexbyte (stringhexstring) {hexstring= Hexstring.replace (" ",""); if((hexstring.length%2) !=0) hexstring+=" "; byte[] Returnbytes =New byte[Hexstring.length/2];  for(inti =0; i < returnbytes.length; i++) Returnbytes[i]= Convert.tobyte (hexstring.substring (i *2,2), -); returnreturnbytes; }  /// <summary>        ///byte array to 16 binary string/// </summary>        /// <param name= "bytes" ></param>        /// <returns></returns>         Public Static stringBYTETOHEXSTR (byte[] bytes) {            stringReturnstr =""; if(Bytes! =NULL)            {                 for(inti =0; I < bytes. Length; i++) {Returnstr+ = Bytes[i]. ToString ("X2"); }             }            returnReturnstr; }  /// <summary>        ///convert from Chinese characters to 16 binary/// </summary>        /// <param name= "s" ></param>        /// <param name= "CharSet" >coding, such as "Utf-8", "gb2312"</param>        /// <param name= "Fenge" >whether each character trailing characters Comma separated</param>       /// <returns></returns>         Public Static stringTohex (stringSstringCharSetBOOLFenge) {            if((s.length%2) !=0) {s+=" ";//Space//throw new ArgumentException ("s is not valid Chinese string!");} System.Text.Encoding CHS=System.Text.Encoding.GetEncoding (CharSet); byte[] bytes =CHS.            GetBytes (s); stringstr ="";  for(inti =0; I < bytes. Length; i++) {str+=string. Format ("{0:x}", Bytes[i]); if(Fenge && (i! = bytes. Length-1) ) {str+=string. Format ("{0}",","); }             }            returnStr.         ToLower (); }  ///<summary>        ///convert from 16 into Chinese/// </summary>        /// <param name= "hex" ></param>        /// <param name= "CharSet" >coding, such as "Utf-8", "gb2312"</param>       /// <returns></returns>         Public Static stringUnhex (stringHexstringCharSet) {           if(Hex = =NULL)                Throw NewArgumentNullException ("Hex"); Hex= Hex. Replace (",",""); Hex= Hex. Replace ("\ n",""); Hex= Hex. Replace ("\\",""); Hex= Hex. Replace (" ",""); if(Hex. Length%2!=0) {hex+=" -";//Space             }            //you need to convert hex into a byte array.             byte[] bytes =New byte[Hex. Length/2];  for(inti =0; I < bytes. Length; i++)            {                Try                {                    //each of the two characters is a byte. Bytes[i] =byte. Parse (Hex. Substring (i *2,2), System.Globalization.NumberStyles.HexNumber); }                Catch                {                    //Rethrow An exception with custom message.                    Throw NewArgumentException ("Hex is not a valid hex number!","Hex"); }} System.Text.Encoding CHS=System.Text.Encoding.GetEncoding (CharSet); returnCHS.         GetString (bytes); }//The above article is reproduced!

C # 16 conversions between strings and byte arrays

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.