直接贴代码。
public static string StringToBinary(string str)
{
byte[] data = Encoding.ASCII .GetBytes(str);
StringBuilder strResult = new StringBuilder(data.Length * 4);
foreach (byte b in data)
{
strResult.Append(Convert.ToString(b, 2).PadLeft(4, “0”));
}
string binary = strResult.ToString();
return binary;
public static string StringToBinary(string str)
{
byte[] data = Encoding.ASCII .GetBytes(str);
StringBuilder strResult = new StringBuilder(data.Length * 4);
foreach (byte b in data)
{
strResult.Append(Convert.ToString(b, 2).PadLeft(4, “0”));
}
string binary = strResult.ToString();
return binary;
}
本人传入的字符例如是“01”,结果返回的是110000 110001,这是怎么回事?为啥前面多了两个1?
解决方案
10
Convert.ToInt32(str, 2);
这样就行了
10
这俩是字符”0″和”1″的asc值48 49,不是多了俩1
5
百度一下”C# 字符转十六进制”就有很多方法,本人用vb.net,没试过c#转,你试试吧
例如http://www.cnblogs.com/zjbtony/archive/2012/04/13/2445055.html
例如http://www.cnblogs.com/zjbtony/archive/2012/04/13/2445055.html
/// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; }
10
var s = "01"; Console.WriteLine(s.PadLeft(s.Length + 8 - (s.Length % 8), "0"));
5
string c = string.Format(“{0,4:X4}”, str);