C#字符串读取txt并且转ascll
时间: 2023-06-30 18:17:47 浏览: 80
你可以使用C#中的System.IO命名空间中的StreamReader类来读取文本文件中的字符串,并使用System.Text中的Encoding.ASCII.GetBytes()方法将读取的字符串转换成ASCII码。以下是一个示例代码,可以读取指定路径下的文本文件,并将内容转换成ASCII码输出到控制台:
```
using System;
using System.IO;
using System.Text;
string filePath = "your_file_path.txt";
// 创建一个StreamReader对象来读取文件
StreamReader reader = new StreamReader(filePath);
// 读取文件中的所有内容
string content = reader.ReadToEnd();
// 关闭StreamReader对象
reader.Close();
// 将读取的字符串转换成ASCII码
byte[] asciiBytes = Encoding.ASCII.GetBytes(content);
// 输出转换后的ASCII码到控制台
foreach (byte b in asciiBytes)
{
Console.Write(b + " ");
}
```
注意,在转换字符串为ASCII码时,也需要确保文件路径正确,并且需要适当地处理异常情况。
相关问题
C语言字符串转ASCLL码存数组
在C语言中,字符串是由一系列字符组成的字符数组,每个字符都有对应的ASCII码。我们可以通过遍历字符串,将每个字符的ASCII码存储到一个整型数组中,从而实现字符串转ASCII码存数组的功能。下面是一个示例代码:
```c
#include <stdio.h>
int main() {
char str[] = "Hello, world!";
int ascii[100];
int i = 0;
while (str[i] != '\0') {
ascii[i] = (int)str[i];
i++;
}
printf("ASCII codes of the string: ");
for (int j = 0; j < i; j++) {
printf("%d ", ascii[j]);
}
return 0;
}
```
该代码将字符串"Hello, world!"转换为对应的ASCII码存储到整型数组ascii中,并输出该数组中的所有元素。需要注意的是,由于ASCII码的范围是0~127,因此我们可以使用char类型来存储ASCII码,也可以使用int类型来存储。如果使用char类型存储,需要将每个字符强制转换为int类型,否则会出现负数的情况。
C++字符串转二进制ascll码
以下是将一个C++字符串转换为二进制ASCII码的代码示例:
```c++
#include <iostream>
#include <bitset>
int main()
{
std::string str = "Hello World";
for (char c : str)
{
std::bitset<8> binary(c);
std::cout << binary.to_string() << " ";
}
return 0;
}
```
这个程序将字符串 "Hello World" 转换为二进制ASCII码并打印输出。每个字符都被转换为一个8位二进制数,并且用空格分隔开来。注意,使用 std::bitset 可以方便地将整数转换为二进制数。