字符串到C#中的二进制

我有一个函数将字符串转换为hex,因此,

public static string ConvertToHex(string asciiString) { string hex = ""; foreach (char c in asciiString) { int tmp = c; hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString())); } return hex; } 

你能帮我把另一个字符串写成基于我的样本函数的二进制函数吗?

 public static string ConvertToBin(string asciiString) { string bin = ""; foreach (char c in asciiString) { int tmp = c; bin += String.Format("{0:x2}", (uint)System.Convert.????(tmp.ToString())); } return bin; } 

干得好:

 public static byte[] ConvertToByteArray(string str, Encoding encoding) { return encoding.GetBytes(str); } public static String ToBinary(Byte[] data) { return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0'))); } // Use any sort of encoding you like. var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII)); 

听起来你基本上想要一个ASCII字符串,或者更好的是,一个byte [](因为你可以使用你喜欢的编码模式将字符串编码为byte [])成为一串零和一个字符串? 即101010010010100100100101001010010100101001010010101000010111101101010

这将为你做到这一点……

 //Formats a byte[] into a binary string (010010010010100101010) public string Format(byte[] data) { //storage for the resulting string string result = string.Empty; //iterate through the byte[] foreach(byte value in data) { //storage for the individual byte string binarybyte = Convert.ToString(value, 2); //if the binarybyte is not 8 characters long, its not a proper result while(binarybyte.Length < 8) { //prepend the value with a 0 binarybyte = "0" + binarybyte; } //append the binarybyte to the result result += binarybyte; } //return the result return result; } 

下面将给出每个字符的低字节的hex编码,它看起来像你要求的:

 StringBuilder sb = new StringBuilder(); foreach (char c in asciiString) { uint i = (uint)c; sb.AppendFormat("{0:X2}", (i & 0xff)); } return sb.ToString(); 

这是一个扩展function:

  public static string ToBinary(this string data, bool formatBits = false) { char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))]; int index = 0; for (int i = 0; i < data.Length; i++) { string binary = Convert.ToString(data[i], 2).PadLeft(8, '0'); for (int j = 0; j < 8; j++) { buffer[index] = binary[j]; index++; } if (formatBits && i < (data.Length - 1)) { buffer[index] = ' '; index++; } } return new string(buffer); } 

您可以像以下一样使用它:

 Console.WriteLine("Testing".ToBinary()); 

如果添加'true'作为参数,它将自动分隔每个二进制序列。