Built-in function to convert from string to byte

I have the following function:

public static byte[] StringToByte(string str)
{
    int length = str.Length;
    byte[] ba = new byte[length];
    for (int i = 0; i < length; i++)
    {           
        ba[i] = (byte)str[i];
    }
    return ba;
}

I wonder if there is a built-in function for this method?

+3
source share
6 answers
System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
byte[] bytes= encoding.GetBytes(stringData);
+6
source
System.Text.Encoding.GetBytes(string)
+9
source

. - . , - , . ? ASCII- ? ?

:

http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx

, , , ASCIIEncoding.

.NET Framework Encoding Unicode :

.NET Framework Encoding Unicode :

  • ASCIIEncoding Unicode 7- ASCII. U + 0000 U + 007F. 20127. ASCII.
  • UTF7Encoding Unicode UTF-7. Unicode. 65000. UTF7.
  • UTF8Encoding Unicode UTF-8. Unicode. 65001. UTF8.
  • UnicodeEncoding Unicode UTF-16. ( 1200), ( 1201). Unicode BigEndianUnicode.
  • UTF32Encoding Unicode UTF-32. ( 12000), ( 12001). UTF32. ASCIIEncoding Unicode 7- ASCII. U + 0000 U + 007F. 20127. ASCII.
  • UTF7Encoding Unicode UTF-7. Unicode. 65000. UTF7.
  • UTF8Encoding Unicode UTF-8. Unicode. 65001. UTF8.
  • UnicodeEncoding Unicode UTF-16. ( 1200), ( 1201). Unicode BigEndianUnicode.
  • UTF32Encoding Unicode UTF-32. ( 12000), ( 12001). UTF32.
+4
+2

, :

public static byte[] StrToByteArray(string str) {
    System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}

ASCIIEn , .

+2
string s = "Like this";
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(s);
0

Source: https://habr.com/ru/post/1737480/


All Articles