在C#中将字符串转换为二进制

我有一个函数可以将字符串转换为十六进制,

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;

}

您能帮我根据我的示例函数向Binary函数写另一个字符串吗?

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;

}

回答:

干得好:

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));

以上是 在C#中将字符串转换为二进制 的全部内容, 来源链接: utcz.com/qa/427449.html

回到顶部