当前位置: 首页 > news >正文

C# byte[]字节数组常用的一些操作。

一、字节组与位组的转化

// 将 binarylist(可能是 byte[] 或 List<byte>)转换为 BitArray
BitArray myBit = new BitArray(binarylist);// 更新指定位(index)的二进制值,设置为 value(true 或 false,代表 1 或 0)
myBit.Set(index, value);// 计算转换后的字节数组长度:(位数 + 7) / 8,确保足够存储所有位
byte[] Newbyte = new byte[(myBit.Length - 1) / 8 + 1];// 将 BitArray 的数据复制到 Newbyte 中
myBit.CopyTo(Newbyte, 0);

字节数组长度计算(向上取整)

(myBit.Length - 1) / 8 + 1

逻辑:通过整数除法实现向上取整。

整数除法会截断小数部分,例如:

7 / 8 = 0,  8 / 8 = 1,  9 / 8 = 1

+ 1:补偿截断的部分,确保结果向上取整。

示例

Length = 8 → (7)/8 +1 = 0+1 = 1(正确)。

Length = 9 → (8)/8 +1 = 1+1 = 2(正确)。

Math.Ceiling(myBit.Length / 8.0)

逻辑:直接数学向上取整。

8.0 强制浮点除法,保留小数部分。

Math.Ceiling 对结果向上取整。

示例

Length = 8 → 8/8.0 = 1.0 → Ceiling(1.0) = 1

Length = 9 → 9/8.0 ≈ 1.125 → Ceiling(1.125) = 2

进阶版(位操作):

// 获取/设置指定位
bool GetBit(byte[] data, int bitPosition)
{int bytePos = bitPosition / 8;int bitPos = bitPosition % 8;return (data[bytePos] & (1 << bitPos)) != 0;
}void SetBit(ref byte[] data, int bitPosition, bool value)
{int bytePos = bitPosition / 8;int bitPos = bitPosition % 8;if (value)data[bytePos] |= (byte)(1 << bitPos);elsedata[bytePos] &= (byte)~(1 << bitPos);
}// 位数组转换
byte[] ToByteArray(BitArray bits)
{byte[] bytes = new byte[(bits.Length - 1) / 8 + 1];bits.CopyTo(bytes, 0);return bytes;
}

二、两个字节合并为一个字节组 

// 输入数据
byte[] prebyte = { 1, 2 };
byte[] Newbyte = { 3, 4 };// 合并数组
byte[] allbyte = new byte[prebyte.Length + Newbyte.Length];
Buffer.BlockCopy(prebyte, 0, allbyte, 0, prebyte.Length);
Buffer.BlockCopy(Newbyte, 0, allbyte, prebyte.Length, Newbyte.Length);// 输出结果:{1, 2, 3, 4}
Console.WriteLine(string.Join(", ", allbyte));

进阶版(合并与分割):

// 合并多个字节数组(优化版)
byte[] Combine(params byte[][] arrays)
{int totalLength = arrays.Sum(a => a?.Length ?? 0);byte[] result = new byte[totalLength];int offset = 0;foreach (var array in arrays){if (array != null && array.Length > 0){Buffer.BlockCopy(array, 0, result, offset, array.Length);offset += array.Length;}}return result;
}// 分割字节数组
List<byte[]> Split(byte[] source, int chunkSize)
{var chunks = new List<byte[]>();for (int i = 0; i < source.Length; i += chunkSize){int remaining = source.Length - i;int currentChunkSize = Math.Min(remaining, chunkSize);byte[] chunk = new byte[currentChunkSize];Buffer.BlockCopy(source, i, chunk, 0, currentChunkSize);chunks.Add(chunk);}return chunks;
}

 

三、两个字节组是否相等

bool CompareArray(byte[] bt1, byte[] bt2)
{if (bt1 == null || bt2 == null)return bt1 == bt2;if (bt1.Length != bt2.Length)return false;for (int i = 0; i < bt1.Length; i++){if (bt1[i] != bt2[i])return false;}return true;
}

进阶版(比较与查找) :

// 高性能比较(支持offset和length)
bool SequenceEqual(byte[] first, int firstOffset, byte[] second, int secondOffset, int length)
{if (first == null || second == null)return first == second;if (first.Length < firstOffset + length || second.Length < secondOffset + length)return false;for (int i = 0; i < length; i++){if (first[firstOffset + i] != second[secondOffset + i])return false;}return true;
}// 查找子数组位置
int IndexOfSubarray(byte[] source, byte[] pattern)
{for (int i = 0; i <= source.Length - pattern.Length; i++){bool match = true;for (int j = 0; j < pattern.Length; j++){if (source[i + j] != pattern[j]){match = false;break;}}if (match) return i;}return -1;
}

四、长度与内存计算

byte[] data = new byte[1024];// 获取字节数
int byteCount = data.Length;// 转换为KB/MB/GB
double kb = data.Length / 1024.0;
double mb = data.Length / (1024.0 * 1024.0);// 内存占用(包括数组开销)
long totalMemory = Buffer.ByteLength(data) + IntPtr.Size; // 数组头信息

http://www.xdnf.cn/news/80245.html

相关文章:

  • 基于LightGBM-TPE算法对交通事故严重程度的分析与可视化
  • 告别网页!体验更丝滑的大模型PC客户端横评
  • 11、Refs:直接操控元素——React 19 DOM操作秘籍
  • 在 Windows 下安装 Dify 教程
  • 准确--CentOS 7 配置 Chrony 同步阿里云 NTP 时间服务器及手动同步指南
  • 蓝牙 6.0 发布,解锁无线科技新可能
  • MQTTClient_message 源码深度解析与架构设计
  • Function calling, 模态上下文协议(MCP),多步能力协议(MCP) 和 A2A的区别
  • Jenkins plugin 的用法和示例
  • Python 设计模式:桥接模式
  • 电商虚拟户分账系统:破解电商资金管理难题的密钥
  • 数据安全,从治理体系开始认清全局
  • 【音视频】AAC-ADTS分析
  • transformer预测寿命
  • 【音视频】FFmpeg内存模型
  • 香港免费云服务器申请教程,配置4核8G
  • 【Maven】配置文件
  • 网络威胁情报 | Friday Overtime Trooper
  • VB.NET 2008影音播放器开发指南
  • 量子计算在密码学中的应用与挑战:重塑信息安全的未来
  • Git,本地上传项目到github
  • 超越GPT-4?下一代大模型的技术突破与挑战
  • OpenLDAP 管理 ELK 用户
  • 运行neo4j.bat console 报错无法识别为脚本,PowerShell 教程:查看语言模式并通过注册表修改受限模式
  • DeepSeek开源引爆AI Agent革命:应用生态迎来“安卓时刻”
  • 【Python】Selenium切换网页的标签页的写法(全!!!)
  • 力扣hot100 LeetCode 热题 100 Java 哈希篇
  • Spring之我见 - Spring MVC重要组件和基本流程
  • N8N 官方 MCP 节点实战指南:AI 驱动下的多工具协同应用场景全解析
  • 多台电脑切换解决方案:KVM 切换器