C# 将string转换成ascii码
时间: 2023-09-30 18:07:40 浏览: 263
字符串转换为ASCII(C#)
在C#中,可以使用以下方法将字符串转换为ASCII码:
方法一:
```csharp
string str = "abc";
StringBuilder ascii = new StringBuilder();
foreach (char c in str)
{
int asciiValue = (int)c;
ascii.Append(asciiValue.ToString() + " ");
}
string asciiString = ascii.ToString();
Console.WriteLine(asciiString);
```
这个方法将字符串中的每个字符转换为对应的ASCII码,并将结果以字符串形式输出。
方法二:
```csharp
string str = "abc";
byte\[\] bytes = System.Text.Encoding.ASCII.GetBytes(str);
StringBuilder ascii = new StringBuilder();
foreach (byte b in bytes)
{
ascii.Append(b.ToString() + " ");
}
string asciiString = ascii.ToString();
Console.WriteLine(asciiString);
```
这个方法使用`System.Text.Encoding.ASCII.GetBytes()`将字符串转换为ASCII码的字节数组,然后将每个字节转换为对应的ASCII码,并将结果以字符串形式输出。
希望这个回答对你有帮助!\[1\]\[2\]
#### 引用[.reference_title]
- *1* *3* [接收的String类型与ASCII码之间的转换](https://blog.csdn.net/Stuomasi_xiaoxin/article/details/129372426)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [C# string ASCII码 16进制转换](https://blog.csdn.net/heihei233/article/details/125346252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文