How do you convert a string to ascii to binary in C#?(如何在 C# 中将字符串转换为 ascii 到二进制?)
问题描述
不久前(高中一年级),我请一位非常优秀的 C++ 程序员,他是一名大三学生,制作了一个将字符串转换为二进制的简单应用程序.他给了我以下代码示例:
A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the following code sample:
void ToBinary(char* str)
{
char* tempstr;
int k = 0;
tempstr = new char[90];
while (str[k] != ' ')
{
itoa((int)str[k], tempstr, 2);
cout << "
" << tempstr;
k++;
}
delete[] tempstr;
}
所以我想我的问题是如何在 C# 中获得与 itoa 函数等效的函数?或者如果没有,我怎么能达到同样的效果?
So I guess my question is how do I get an equivalent to the itoa function in C#? Or if there is not one how could I achieve the same effect?
推荐答案
这在 C# 中很容易做到.
This is very easy to do with C#.
var str = "Hello world";
With LINQ
foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
Console.WriteLine(letter);
}
Pre-LINQ
foreach (char letter in str.ToCharArray())
{
Console.WriteLine(Convert.ToString(letter, 2));
}
这篇关于如何在 C# 中将字符串转换为 ascii 到二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中将字符串转换为 ascii 到二进制?
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
