gpt4 book ai didi

c# - C# 字符串转二进制

转载 作者:IT王子 更新时间:2023-10-29 04:29:18 24 4
gpt4 key购买 nike

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

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

你能帮我根据我的示例函数将另一个字符串写入二进制函数吗?

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# - C# 字符串转二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5664345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com