C # Serial Communication: hexadecimal conversion between string and byte array .,

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

C # Serial Communication: hexadecimal conversion between string and byte array .,

1.Converts a decimal string to a hexadecimal string.

// Convert decimal to binary
Console. WriteLine ("binary representation of decimal 166:" + Convert. ToString (166, 2 ));
// Convert decimal to octal
Console. WriteLine ("octal representation of decimal 166:" + Convert. ToString (166, 8 ));
// Convert decimal to hexadecimal
Console. WriteLine ("hexadecimal representation of decimal 166:" + Convert. ToString (166, 16 ));

// Convert binary to decimal
Console. WriteLine ("decimal representation of binary 111101:" + Convert. ToInt32 ("111101", 2 ));
// Octal to decimal
Console. WriteLine ("octal 44 in decimal format:" + Convert. ToInt32 ("44", 8 ));
// Convert hexadecimal to decimal
Console. WriteLine ("hexadecimal CC in decimal format:" + Convert. ToInt32 ("CC", 16 ));

2.Hexadecimal conversion between strings and byte Arrays

Private string StringToHexString (string s, Encoding encode)
{
Byte [] B = encode. GetBytes (s); // string programming byte array according to the specified Encoding
String result = string. Empty;
For (int I = 0; I <B. Length; I ++) // convert byte to hexadecimal characters separated by %
{
Result + = "%" + Convert. ToString (B [I], 16 );
}
Return result;
}
Private string HexStringToString (string hs, 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];
// Convert characters to hexadecimal bytes one by one
For (int I = 0; I <chars. Length; I ++)
{
B [I] = Convert. ToByte (chars [I], 16 );
}
// Convert the byte array into a string according to the specified Encoding
Return encode. GetString (B );
}

 

3. /// <summary>
/// Convert string to hexadecimal byte array
/// </Summary>
/// <Param name = "hexString"> </param>
/// <Returns> </returns>
Private static byte [] strtohexbyte (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>
/// Convert byte array to hexadecimal string
/// </Summary>
/// <Param name = "bytes"> </param>
/// <Returns> </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 Chinese characters to hexadecimal
/// </Summary>
/// <Param name = "s"> </param>
/// <Param name = "charset"> encoding, such as "UTF-8" and "gb2312" </param>
/// <Param name = "fenge"> whether to separate each character with commas </param>
/// <Returns> </returns>
Public static string ToHex (string s, string charset, bool fenge)
{
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 );
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>
/// Convert from hexadecimal to Chinese Characters
/// </Summary>
/// <Param name = "hex"> </param>
/// <Param name = "charset"> encoding, such as "UTF-8" and "gb2312" </param>
/// <Returns> </returns>
Public static string UnHex (string hex, string charset)
{
If (hex = null)
Throw new ArgumentNullException ("hex ");
Hex = hex. Replace (",","");
Hex = hex. Replace ("\ n ","");
Hex = hex. Replace ("\\","");
Hex = hex. Replace ("","");
If (hex. Length % 2! = 0)
{
Hex + = "20"; // Space
}
// You Need to Convert hex to a byte array.
Byte [] bytes = new byte [hex. Length/2];

For (int I = 0; I <bytes. Length; I ++)
{
Try
{
// Each 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 chs. GetString (bytes );
}

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.