在作业中需求是要求把字符串转成0101这样的二进制流,根据ASCII码把每一个字符对应7位二进制,再根据这个二进制0与1进行不同操作,与别的客户进行交互,同时接收方也要把接收到的二进制流转换成对应的字符串获取数据。
方法如下:
方法如下:
字符串转二进制流:
//Char字符转成7位二进制
public string StringToBinary(string ss)
{
byte[] u = Encoding.ASCII.GetBytes(ss);
string binaryNum = string.Empty;
string result = string.Empty;
foreach (byte a in u)
{
binaryNum = Convert.ToString(a, 2);
if (binaryNum.Length < 7)
{
for (int i = 0; i < 7 - binaryNum.Length; i++)
{
binaryNum = '0' + binaryNum;
}
}
result += binaryNum;
}
return result;
}
存储二进制的字符串转成对应的数据
char[] np = namepwd .ToCharArray();//"1000001000000001100010110010".ToCharArray();
string username = "";
string password = "";
bool flag = false;
string a = "";
for (int i = 0; i < np.Length; i++)
{
a += np[i];
if (a.Length % 7 == 0)
{
if (Convert.ToInt32(a, 2) == 0)
{
flag = true;
a = string.Empty;
continue;
}
if (flag )
password += Convert.ToChar(Convert.ToInt32(a,2));
else
username += Convert.ToChar(Convert.ToInt32(a,2));
a = string.Empty;
}
}