C # 16 conversions between strings and byte arrays

Source: Internet
Author: User
Tags binary to decimal decimal to binary

1. How to convert a decimal number string to a hexadecimal number in C #//Decimal to Binary Console.WriteLine ("Decimal 166 binary notation:" +convert.tostring (166, 2));// Decimal to Octal Console.WriteLine ("Octal Representation of decimal 166:" +convert.tostring (166, 8));//Decimal to hexadecimal Console.WriteLine ("Decimal 166 hexadecimal representation:"   +convert.tostring (166, 16)); Binary to Decimal Console.WriteLine ("Decimal Representation of binary 111101:" +convert.toint32 ("111101", 2));//octal to Decimal Console.WriteLine ("Octal 44 Decimal notation: "+convert.toint32 (" 44 ", 8));//hexadecimal to decimal Console.WriteLine (" Decimal Representation of hexadecimal cc: "+convert.toint32 (" CC ", 16)); 2.  In the serial communication process, it is often used to convert between 16 and string, byte array//private string stringtohexstring (string s,encoding encode) {byte[] b = encode. GetBytes (s);//The string is programmed into a byte array by the specified encoding string result = String.            Empty; for (int i = 0; i < b.length; i++)//byte to 16 characters, separated by% {result + = "%" +convert.tostring (B[i], 1            6);        } return result; } private String Hexstringtostring (string hs, Encoding encode) {//Divide the string with%, and remove the null character Stri Ng[] chars = hs. SPlit (new char[]{'% '},stringsplitoptions.removeemptyentries); Byte[] B = new Byte[chars.            Length]; Each character becomes 16 bytes of data for (int i = 0; i < chars. Length;            i++) {B[i] = Convert.tobyte (chars[i], 16); }//Follow the specified encoding to change the byte array to the string return encode.        GetString (b); }///<summary>///String to 16 byte array///</summary>//<param name= "hexstring" >        </param>//<returns></returns> private static byte[] Strtotohexbyte (string hexstring)           {hexstring = Hexstring.replace ("", "");            if (hexstring.length% 2)! = 0) HexString + = "";            byte[] returnbytes = new BYTE[HEXSTRING.LENGTH/2]; for (int i = 0; i < returnbytes.length; i++) returnbytes[i] = Convert.tobyte (hexstring.substring (i * 2,            2), 16);         return returnbytes; }//<summary>// byte array to 16 binary strings///</summary>//<param name= "bytes" ></param>//&LT;RETURNS&GT;&L            t;/returns> public static string bytetohexstr (byte[] bytes) {String returnstr = ""; if (bytes! = null) {for (int i = 0; i < bytes. Length; i++) {returnstr + = Bytes[i].                 ToString ("X2");         }} return returnstr;        }///<summary>//Convert from Kanji to 16///</summary>//<param name= "s" ></param> <param name= "CharSet" > Encoding, such as "Utf-8", "gb2312" </param>//<param name= "Fenge" > whether each word trailing characters comma-delimited &l t;/param>//<returns></returns> public static string Tohex (string s, String charset, bool Fe Nge) {if ((s.length% 2)! = 0) {s + = "";//Space//throw new Ar Gumentexception ("s is not valid CHInese string! ");}            System.Text.Encoding CHS = System.Text.Encoding.GetEncoding (charset); byte[] bytes = chs.            GetBytes (s);            String str = ""; for (int i = 0; i < bytes. Length; i++) {str + = string.                Format ("{0:x}", Bytes[i]); if (Fenge && (i! = bytes. Length-1)) {str + = string.                 Format ("{0}", ","); }} return str.         ToLower ();        }///<summary>///from 16 into Chinese characters//</summary>//<param name= "hex" ></param>        <param name= "CharSet" > Codes, such as "Utf-8", "gb2312" </param>//<returns></returns> public static string Unhex (string hex, String charset) {if (hex = = null) throw new Argum             Entnullexception ("hex"); Hex = hex.             Replace (",", ""); Hex = hex.             Replace ("\ n", ""); Hex = Hex.             Replace ("\ \", ""); Hex = hex.            Replace ("", ""); if (hex.            Length% 2 = 0) {hex + = "20";//space}//need to convert hex to byte array. byte[] bytes = new Byte[hex.           LENGTH/2]; for (int i = 0; i < bytes. Length;                     i++) {try {//Every 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 new ArgumentException ("hex is not a valid hex number!", "hex");            }} System.Text.Encoding CHS = System.Text.Encoding.GetEncoding (charset); Return to CHS.         GetString (bytes); }

    <summary>///    16 binary strings converted to 8-bit binary arrays///</summary>//    <param name= "hexstring" ></ param>    //<returns></returns> private byte[] Hexstrtobytearray (string hexstring)    {        hexstring = Hexstring.replace ("", "");        if ((hexstring.length% 2)! = 0)            throw new ArgumentException ("hexadecimal string length is incorrect");        byte[] buffer = new BYTE[HEXSTRING.LENGTH/2];        for (int i = 0; i < buffer. Length; i++)        {            Buffer[i] = Convert.tobyte (hexstring.substring (i * 2, 2). Trim (), 0x10);        }        return buffer;    }

C # 16 conversions between strings and byte arrays

Related Article

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.