当前位置: 首页 > 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; // 数组头信息

相关文章:

  • 实战交易策略 篇十七:翻倍黑马交易策略
  • npm的基本使用安装所有包,安装删除指定版本的包,配置命名别名
  • 解决方案 | 晶尊微智能马桶着座感应模块
  • nodejs的包管理工具介绍,npm的介绍和安装,npm的初始化包 ,搜索包,下载安装包
  • Git远程操作
  • Java MCP客户端SDK实现
  • Unity 带碰撞的粒子效果
  • Linux 系统监控进阶:htop 命令详解与高效运维
  • 已安装爱思助手和Apple相关驱动,但仍无法有线连接iPhone热点,且网络适配器没有Apple Mobile Device Ethernet,问题解决
  • 比特币三种扩容路径Nubit、Babylon、Bitlayer分析
  • java的反编译命令
  • 【Hive入门】Hive架构与组件深度解析:从核心组件到生态协同
  • 关于RPC
  • 物联网 (IoT) 安全简介
  • Oracle数据库学习之路-目录
  • Nginx openresty web服务 与 Go 原生web服务性能对比
  • 跨平台.NET 版本 使用率排名
  • CAN总线接口卡有什么优势
  • 4.21—4.22学习总结 JavaWeb:HTML-CSS
  • 火山RTC 5 转推CDN 布局合成规则
  • 福建一季度GDP为13232.38亿元,同比增长5.7%
  • 国际货币基金组织:将今年美国经济增长预期下调0.9个百分点至1.8%
  • 洛阳白马寺存争议的狄仁杰墓挂牌,当地文物部门:已确认
  • 新闻1+1丨居民水电气计量收费乱象,如何治?
  • 习近平致电祝贺诺沃亚当选连任厄瓜多尔总统
  • 从南宋遗韵到海派风情,解码江南服饰美学基因