在帮助里找了好久也没找到相应的函数,不知道是不是我找的方向不对所以没有找到.
自己写了个,没有做数据验证^_^
自己写了个,没有做数据验证^_^
public class BitOperator
{
/// <summary>
/// 将字节转换成二进制字符串
/// </summary>
/// <param name="valByte">字节</param>
/// <returns>二进制字符串</returns>
public string BitConvert(byte valByte)
{
string valString = "00000000";
int valInt = System.Convert.ToInt32(valByte);
if(valInt != 0)
{
int[] bitArray = new int[]{0,0,0,0,0,0,0,0};
valString = "";
for(int i = 7; i >= 0; i--)
{
bitArray[i] = valInt%2;
valInt /= 2;
if(valInt == 1)
{
bitArray[i - 1] = 1;
break;
}
}
for(int i = 0; i < bitArray.Length; i++)
{
valString += bitArray[i].ToString();
}
}
return valString;
}
/// <summary>
/// 将二进制字符串转换成字节
/// </summary>
/// <param name="valString">二进制字符串</param>
/// <returns>字节</returns>
public byte BitConvert(string valString)
{
byte valByte = System.Convert.ToByte(0);
if(valString != "00000000")
{
int valInt = 0;
for(int i = 7,j = 0; i >= 0; i--,j++)
{
if(valString[i] != '0')
{
valInt += System.Convert.ToInt32(Math.Pow(2,j));
}
}
valByte =System.Convert.ToByte(valInt);
}
return valByte;
}
}
{
/// <summary>
/// 将字节转换成二进制字符串
/// </summary>
/// <param name="valByte">字节</param>
/// <returns>二进制字符串</returns>
public string BitConvert(byte valByte)
{
string valString = "00000000";
int valInt = System.Convert.ToInt32(valByte);
if(valInt != 0)
{
int[] bitArray = new int[]{0,0,0,0,0,0,0,0};
valString = "";
for(int i = 7; i >= 0; i--)
{
bitArray[i] = valInt%2;
valInt /= 2;
if(valInt == 1)
{
bitArray[i - 1] = 1;
break;
}
}
for(int i = 0; i < bitArray.Length; i++)
{
valString += bitArray[i].ToString();
}
}
return valString;
}
/// <summary>
/// 将二进制字符串转换成字节
/// </summary>
/// <param name="valString">二进制字符串</param>
/// <returns>字节</returns>
public byte BitConvert(string valString)
{
byte valByte = System.Convert.ToByte(0);
if(valString != "00000000")
{
int valInt = 0;
for(int i = 7,j = 0; i >= 0; i--,j++)
{
if(valString[i] != '0')
{
valInt += System.Convert.ToInt32(Math.Pow(2,j));
}
}
valByte =System.Convert.ToByte(valInt);
}
return valByte;
}
}