# Viyi.Bytes **Repository Path**: jamesfancy/Viyi.Bytes ## Basic Information - **Project Name**: Viyi.Bytes - **Description**: 从 Viyi.Util 1.x 中分离出来,专门处理字节的工具 - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-01-03 - **Last Updated**: 2026-03-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Viyi.Bytes Viyi.Bytes is coming soon. ## 1. 关于 (About) Viyi.Bytes 是从 [Viyi.Util][viyi_util] 中分离出来的,专注于处理二进制数据 (bytes) 和其他数据类型(除字符串)之间的转换。 Viyi.Bytes 使用[木兰宽松许可证第 2 版 (Mulan Permissive Software License, Version 2)][mulanpsl2]。 > 原 Viyi.Util 涉及的范围非常多,过于分散,而且其中部分工具已经有更好的替代品。所以没有对 Viyi.Util 直接进行升级,而是将其拆分: > > * [Viyi.Util V2][viyi_util] 完全重构的工具集,对常用数据结构和集合等进行扩展。 > * [Viyi.Strings][viyi_strings] 用于处理字符串 (Viyi.Strings is a string toolkit.) > * [Viyi.Bytes][viyi_util] 用于处理二进制数据,计划中 (Viyi.Bytes is a binary data toolkit, in planning.) ## API 参考 (API Reference) 本节对库中主要 API 进行简明说明与使用示例,包含字节数组与基础类型相互转换的助手方法(大端/小端)。 ### BinaryPrimitives 兼容方法 - `ToInt32Le(byte[] source, int start)` / `ToInt32Be(byte[] source, int start)` - `WriteInt32LittleEndian(byte[] destination, int start, int value)` / `WriteInt32BigEndian(byte[] destination, int start, int value)` 使用示例(大端): ```csharp var buf = new byte[4]; BinaryPrimitives.WriteInt32BigEndian(buf, 0, 0x01020304); int v = BinaryPrimitives.ToInt32Be(buf, 0); // v == 0x01020304 ``` 使用示例(小端): ```cs var buf = new byte[4]; BinaryPrimitives.WriteInt32LittleEndian(buf, 0, 0x01020304); int v = BinaryPrimitives.ToInt32Le(buf, 0); // v == 0x01020304 ``` > 库为常用基础类型(例如 `Int16/UInt16/Int32/UInt32/Int64/UInt64/Single/Double`)生成等价的读写方法,方法命名规则为 `To{Type}Be/To{Type}Le` 与 `Write{Type}BigEndian/Write{Type}LittleEndian`。 ### ByteArrayExtensions 扩展方法 - `byte[]? GetBytes(this IEnumerable values)` — 将序列按大端编码为字节数组(长度 `sizeof(T)*n`)。 - `byte[]? GetBytesLittleEndian(this IEnumerable values)` — 小端编码版本。 - `T[]? ToInt32Array(this byte[]? bytes, int start = 0)` / `ToInt32ArrayLittleEndian(...)` — 将字节数组按单元大小转换为类型数组,支持起始位置与自动处理尾部不足字节(会被忽略)。 使用示例: ```csharp var arr = new int[] { 1, 2, 3 }; var bytes = arr.GetBytes(); // 大端 var back = bytes.ToInt32Array(); ``` ### 单元测试 (Tests) 当前测试项目使用 MSTest(项目 `Viyi.Bytes.Test` 已存在并多目标编译)。建议测试要点: - 覆盖大端与小端读写的互逆性(写入再读取应还原原值)。 - 边界条件:起始偏移、长度不足、空数组/空集合。 - 多目标构建(`net8.0` 与 `net481` / `netstandard2.0`)应通过测试。 运行测试: - Visual Studio: 打开 __Test Explorer__ 并执行 __Run All__。 - CLI: 使用 `dotnet test`(会自动为解决方案中的测试项目运行所有目标框架)。 若要添加新的测试规范或样式规则,请将其记录到 `CONTRIBUTING.md` 中。 [mulanpsl2]: http://license.coscl.org.cn/MulanPSL2 "木兰宽松许可证,第2版" [viyi_util]: https://gitee.com/jamesfancy/Viyi.Util "Viyi.Util" [viyi_strings]: https://gitee.com/jamesfancy/viyi-strings "Viyi.Strings" [viyi_bytes]: https://gitee.com/jamesfancy/viyi-bytes "Viyi.Bytes" [vs_nuget]: https://docs.microsoft.com/zh-cn/nuget/consume-packages/install-use-packages-visual-studio