C # String types and byte[] types convert each other

Source: Internet
Author: User

Convert string type to byte[]:

byte[] ByteArray = System.Text.Encoding.Default.GetBytes (str);

Convert string type to byte[]:

byte[] ByteArray = System.Text.Encoding.Default.GetBytes (str);

Byte[] turn into string:

String str = System.Text.Encoding.Default.GetString (ByteArray);

The string type turns to ASCII byte[]:

("01" turn into byte[] = new byte[]{0x30,0x31})

byte[] ByteArray = System.Text.Encoding.ASCII.GetBytes (str);

Asciibyte[] turn into string:

(byte[] = new byte[]{0x30, 0x31} turns into "01")

String str = System.Text.Encoding.ASCII.GetString (ByteArray);

Byte[] Go to 16 binary format string:

New byte[]{0x30, 0x31} turns into "3031":

Publicstaticstring tohexstring (byte[] bytes)//0XAE00CF = "AE00CF"

{string hexstring = string. Empty;

if (bytes! = null)

{

StringBuilder StrB = new StringBuilder ();

for (int i = 0; i < bytes. Length; i++)

{

Strb.append (Bytes[i]. ToString ("X2"));

}

hexstring = Strb.tostring ();

}return hexstring;

}

16 binary format string to byte[]:

Publicstaticbyte[] GetBytes (string hexstring, Outint discarded)

{

discarded = 0;

String newstring = "";

Char c;//Remove all none a-f, 0-9, charactersfor (int i=0; i

{

c = hexstring[i];if (Ishexdigit (c))

NewString + = C;

Else

discarded++;

}//if odd number of characters, discard last Characterif (newstring.length% 2! = 0) {discarded++;

newstring = newstring.substring (0, newstring.length-1); }

int bytelength = newstring.length/2;byte[] bytes = newbyte[bytelength];string Hex;int j = 0;for (int i=0; i<bytes. Length; i++) {

Hex = new String (new char[] {newstring[j], newstring[j+1]});

Bytes[i] = Hextobyte (hex); j = j+2;

}

return bytes;

}

C # String types and byte[] types convert each other

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.