开放的编程资料库

当前位置:我爱分享网 > C#教程 > 正文

C#字节

在本文中,我们展示了如何在C#中使用字节类型。

byte类型是C#中的一种简单的数字值类型。当处理文件和网络连接时,byte类型主要用于IO操作。

有两种基本的字节类型:

keyword  range         size                     .NET type
sbyte    -128 to 127   Signed 8-bit integer     System.SByte
byte     0 to 255      Unsigned 8-bit integer   System.Byte

清单显示了两种字节类型的关键字、范围、大小和.NET类型。

C#字节和sbyte

在第一个例子中,我们展示了字节类型的基本属性。

byte val1 = 5;
sbyte val2 = -4;

Console.WriteLine(val1);
Console.WriteLine(val2);

Console.WriteLine(val1.GetType());
Console.WriteLine(val2.GetType());

Console.WriteLine("------------------------");

Console.WriteLine(byte.MinValue);
Console.WriteLine(byte.MaxValue);

Console.WriteLine(sbyte.MinValue);
Console.WriteLine(sbyte.MaxValue);

Console.WriteLine("------------------------");

Console.WriteLine(typeof(byte));
Console.WriteLine(typeof(sbyte));
Console.WriteLine(default(byte));
Console.WriteLine(default(sbyte));

程序程序定义bytesbyte类型并打印它们的属性。

Console.WriteLine(val1.GetType());
Console.WriteLine(val2.GetType());

我们可以使用GetType确定变量的类型。

Console.WriteLine(byte.MinValue);
Console.WriteLine(byte.MaxValue);

最小值和最大值由MinValueMaxValue属性确定。

Console.WriteLine(typeof(byte));
Console.WriteLine(typeof(sbyte));

底层.NET类型由typeof关键字确定。

Console.WriteLine(default(byte));
Console.WriteLine(default(sbyte));

类型的默认值通过default关键字返回。

$ dotnet run
5
-4
System.Byte
System.SByte
------------------------
0
255
-128
127
------------------------
System.Byte
System.SByte
System.Byte
0
0

C#字符串转字节

我们使用Encoding将字符串转换为字节,反之亦然。

using System.Text;

string word = "čerešňa";

byte[] data = Encoding.UTF8.GetBytes(word);
Console.WriteLine(string.Join(" ", data));

string word2 = Encoding.UTF8.GetString(data);
Console.WriteLine(word2);

我们有一个包含三个重音字母的单词。

byte[] data = Encoding.UTF8.GetBytes(word);

要将字符串转换为字节,我们使用Encoding.UTF8.GetBytes

string word2 = Encoding.UTF8.GetString(data);

要从字节数组中获取字符串,我们使用Encoding.UTF8.GetString方法。

$ dotnet run
196 141 101 114 101 197 161 197 136 97
čerešňa

这个词有七个字母。在数组中我们有十个字节。这意味着三个重音字母分别由两个字节表示。

C#写入字节到文件

在下一个示例中,我们将一些数据写入文本文件。

public override void Write(byte[] buffer, int offset, int count);

FileStream.Write方法将一个字节块写入文件流。该方法采用三个参数:字节数组、数组中从零开始的字节偏移量,从中开始将字节复制到流中,以及要写入的最大字节数。

using System.Text;

var path = "words.txt";

using FileStream fs = File.Create(path);
byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\nwater");
fs.Write(data, 0, data.Length);

Console.WriteLine("data written to file");

该示例将四个单词写入一个文件。

using FileStream fs = File.Create(path);

我们使用File.Create创建一个新文件。该方法返回一个FileStream

byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\nwater");

我们使用Encoding.UTF8.GetBytes获取文本的字节数

fs.Write(data, 0, data.Length);

我们使用Write将整个字节数组写入文件流。

获取HTML页面

HttpClient.GetByteArrayAsync向指定的Uri发送GET请求,并在异步操作中将响应主体作为字节数组返回。

string url = "http://webcode.me";
HttpClient client = new HttpClient();

byte[] data = await client.GetByteArrayAsync(url);

string fname = "index.html";
File.WriteAllBytes(fname, data);

我们使用GetByteArrayAsync将HTML页面检索到字节数组中。然后我们使用File.WriteAllBytes将字节数组写入文件。

C#文件.ReadAllBytes

File.ReadAllBytes打开一个二进制文件,将文件内容读入字节数组,然后关闭文件。

var path = "favicon.ico";
byte[] data = File.ReadAllBytes(path);

int i = 0;

foreach (byte c in data)
{
    Console.Write("{0:X2} ", c);
    i++;

    if (i % 10 == 0)
    {
        Console.WriteLine();
    }
}

该示例读取一个favicon.ico二进制文件。数据以十六进制格式打印到控制台。

$ dotnet run
00 00 01 00 01 00 10 10 00 00 
00 00 00 00 68 05 00 00 16 00 
00 00 28 00 00 00 10 00 00 00 
20 00 00 00 01 00 08 00 00 00 
00 00 00 01 00 00 00 00 00 00 
00 00 00 00 00 01 00 00 00 00 
00 00 00 00 00 00 FF FF FF 00 
4D 45 3D 00 00 00 00 00 00 00 
...

HttpServer示例

HTTP服务器将其数据写入响应对象的输出流。

using System.Net;
using System.Text;

using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8001/");

listener.Start();

Console.WriteLine("Listening on port 8001...");

while (true)
{
    HttpListenerContext context = listener.GetContext();

    using HttpListenerResponse resp = context.Response;
    resp.Headers.Set("Content-Type", "text/plain");

    string data = "Hello there!";
    byte[] buffer = Encoding.UTF8.GetBytes(data);
    resp.ContentLength64 = buffer.Length;

    using Stream ros = resp.OutputStream;
    ros.Write(buffer, 0, buffer.Length);
}

C#有HttpListener来创建简单的HTTP服务器。我们的服务器发送短信。

using HttpListenerResponse resp = context.Response;
resp.Headers.Set("Content-Type", "text/plain");

在响应标头中,我们将Content-Type设置为text/plain以提示客户端需要什么样的数据。

string data = "Hello there!";
byte[] buffer = Encoding.UTF8.GetBytes(data);

我们将消息转换为字节。

resp.ContentLength64 = buffer.Length;

我们设置内容长度。

using Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);

最后,我们使用Write将字节写入输出流。

$ curl localhost:8001
Hello there!

在本文中,我们使用了C#中的字节类型。

列出所有C#教程。

未经允许不得转载:我爱分享网 » C#字节

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏