Строка к двоичной в С#
У меня есть функция для преобразования строки в шестнадцатеричную,
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;
}
Ответы
Ответ 1
Здесь вы идете:
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));
Ответ 2
Похоже, вы в основном хотите взять строку ASCII или, более предпочтительно, байт [] (так как вы можете закодировать свою строку в байт [], используя предпочтительный режим кодирования), в строку из них и нули? т.е. 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;
}
Ответ 3
Ниже приведено шестнадцатеричное кодирование для младшего байта каждого символа, который выглядит так, как вы просите:
StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
uint i = (uint)c;
sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();
Ответ 4
Здесь функция расширения:
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" в качестве параметра, он автоматически разделит каждую двоичную последовательность.