static List<int> ConvertTextToBinary(int number, int Base)
{
List<int> list = new List<int>();
while (number!=0)
{
list.Add(number % Base);
number = number / Base;
}
list.Reverse();
return list;
}
static void Main(string[] args)
{
string s = "stackoverflow";
int counter=0;
while (counter!=s.Length)
{
int[] a = ConvertTextToBinary(s[counter], 2).ToArray();
for (int i = 0; i < a.Length; i++)
{
Console.Write(a[i]);
}
Console.Write("\n");
counter++;
}
}
我编写了一个将字符串转换为二进制的方法,它的工作正常。但现在我想将二进制转换为字符串,例如:1101000等于h。
答案 0 :(得分:4)
您可以将单个位集转换为字符,如下所示:
int[] h = { 1, 1, 0, 1, 0, 0, 0 };
int result = 0;
int bitValue = 1;
for (int i = h.Length - 1; i >= 0 ; i--)
{
result += h[i] * bitValue;
bitValue *= 2;
}
Console.WriteLine((char)result);
每个位对应2的倍数。从最后一位开始并将位值乘以2,得到你想要的结果。
答案 1 :(得分:4)
用于将byte []转换为字符串
byte[] bytes ;
string base64Data = Convert.ToBase64String (bytes);
或
string strData = Encoding.Default.GetString(bytes);
答案 2 :(得分:3)
static string ConvertBinaryToText(List<List<int>> seq){
return new String(seq.Select(s => (char)s.Aggregate( (a,b) => a*2+b )).ToArray());
}
static void Main(){
string s = "stackoverflow";
var binary = new List<List<int>>();
for(var counter=0; counter!=s.Length; counter++){
List<int> a = ConvertTextToBinary(s[counter], 2);
binary.Add(a);
foreach(var bit in a){
Console.Write(bit);
}
Console.Write("\n");
}
string str = ConvertBinaryToText(binary);
Console.WriteLine(str);//stackoverflow
}