// C# to convert a string to a byte array.public static byte[] StrToByteArray(string str){System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();return encoding.GetBytes(str);}
// C# to convert a byte array to a string.byte [] dBytes = ...string str;System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();str = enc.GetString(dBytes);
public static byte[] StrToByteArray(this string s){List<byte> value = new List<byte>();foreach (char c in s.ToCharArray())value.Add(c.ToByte());return value.ToArray();}
而且,
public static byte[] StrToByteArray(this string s){s = s.Replace(" ", string.Empty);byte[] buffer = new byte[s.Length / 2];for (int i = 0; i < s.Length; i += 2)buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);return buffer;}
bytes[] buffer = UnicodeEncoding.UTF8.GetBytes(string something); //for converting to UTF then get its bytes
bytes[] buffer = ASCIIEncoding.ASCII.GetBytes(string something); //for converting to ascii then get its bytes
const string data = "A string with international characters: Norwegian: ÆØÅæøå, Chinese: 喂 谢谢";var bytes = System.Text.Encoding.UTF8.GetBytes(data);var decoded = System.Text.Encoding.UTF8.GetString(bytes);
static byte[] GetBytes(string str){byte[] bytes = new byte[str.Length * sizeof(char)];System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);return bytes;}
// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME systemstatic string GetString(byte[] bytes){char[] chars = new char[bytes.Length / sizeof(char)];System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);return new string(chars);}
// Input string.const string input = "Dot Net Perls";
// Invoke GetBytes method.// ... You can store this array as a field!byte[] array = Encoding.ASCII.GetBytes(input);
// Loop through contents of the array.foreach (byte element in array){Console.WriteLine("{0} = {1}", element, (char)element);}
// using System.Runtime.InteropServicesunsafe byte[] GetRawBytes(String s){if (s == null) return null;var codeunitCount = s.Length;/* We know that String is a sequence of UTF-16 code unitsand such code units are 2 bytes */var byteCount = codeunitCount * 2;var bytes = new byte[byteCount];fixed(void* pRaw = s){Marshal.Copy((IntPtr)pRaw, bytes, 0, byteCount);}return bytes;}
string myString = //... some string
System.Text.Encoding encoding = System.Text.Encoding.UTF8; //or some other, but prefer some UTF is Unicode is usedbyte[] bytes = encoding.GetBytes(myString);
//next lines are written in response to a follow-up questions:
myString = new string(encoding.GetChars(bytes));byte[] bytes = encoding.GetBytes(myString);myString = new string(encoding.GetChars(bytes));byte[] bytes = encoding.GetBytes(myString);
//how many times shall I repeat it to show there is a round-trip? :-)
我已经写了一个Visual Basic扩展类似于接受的答案,但直接使用. NET内存和编组进行转换,它支持其他方法不支持的字符范围,如UnicodeEncoding.UTF8.GetString或UnicodeEncoding.UTF32.GetString甚至MemoryStream and BinaryFormatter(无效字符,如:):
<Extension> _Public Function ToBytesMarshal(ByRef str As String) As Byte()Dim gch As GCHandle = GCHandle.Alloc(str, GCHandleType.Pinned)Dim handle As IntPtr = gch.AddrOfPinnedObjectToBytesMarshal = New Byte(str.Length * 2 - 1) {}TryFor i As Integer = 0 To ToBytesMarshal.Length - 1ToBytesMarshal.SetValue(Marshal.ReadByte(IntPtr.Add(handle, i)), i)NextFinallygch.Free()End TryEnd Function
<Extension> _Public Function ToStringMarshal(ByRef arr As Byte()) As StringDim gch As GCHandle = GCHandle.Alloc(arr, GCHandleType.Pinned)TryToStringMarshal = Marshal.PtrToStringAuto(gch.AddrOfPinnedObject)Finallygch.Free()End TryEnd Function