byte数据的常用操作函数[转发]
/// <summary>
/// 本类提供了对byte数据的常用操作函数
/// </summary>
public class ByteUtil
{
private static char[] HEX_CHARS = {'','','','','','','','','','','A','B','C','D','E','F'};
private static byte[] BITS = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; /// <summary>
/// 将字节数组转换为HEX形式的字符串, 使用指定的间隔符
/// </summary>
public static string ByteToHex(byte[] buf, string separator)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(int i = ;i < buf.Length;i++)
{
if (i > )
{
sb.Append(separator);
}
sb.Append(HEX_CHARS[buf[i] >> ]).Append(HEX_CHARS[buf[i] & 0x0F]);
}
return sb.ToString();
} /// <summary>
/// 将字节数组转换为HEX形式的字符串, 使用指定的间隔符
/// </summary>
public static string ByteToHex(byte[] buf, char c)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(int i = ;i < buf.Length;i++)
{
if (i > )
{
sb.Append(c);
}
sb.Append(HEX_CHARS[buf[i] >> ]).Append(HEX_CHARS[buf[i] & 0x0F]);
}
return sb.ToString();
} /// <summary>
/// 判断字节数组前几位是否符合一定规则
/// </summary>
/// <param name="data">需要判断的字节数组</param>
/// <param name="pattern">匹配规则</param>
/// <returns>如果匹配返回true</returns>
public static bool IsMatch(byte[] data, params byte[] pattern)
{
if (data == null || data.Length < pattern.Length)
return false; for(int i = ;i < pattern.Length;i++)
{
if (data[i] != pattern[i])
return false;
}
return true;
} /// <summary>
/// 判断指定字节是否为列举的某个值
/// </summary>
/// <param name="value">需要判断的值</param>
/// <param name="choice">可能值</param>
/// <returns>如果与任一个可能值相等则返回true</returns>
public static bool IsMatch(byte value, params byte[] choice)
{
if (choice == null || choice.Length == )
return false; foreach(byte item in choice)
{
if (item == value)
return true;
}
return false;
} /// <summary>
/// 将字节数组转换为HEX形式的字符串, 没有间隔符
/// </summary>
public static string ByteToHex(byte[] buf)
{
return ByteToHex(buf, string.Empty);
} /// <summary>
/// 将字节数组转换为HEX形式的字符串
/// 转换后的字符串长度为字节数组长度的两倍
/// 如: 1, 2 转换为 0102
/// </summary>
public static string ByteToHex(byte b)
{
return string.Empty + HEX_CHARS[b >> ] + HEX_CHARS[b & 0x0F];
} /// <summary>
/// 将字节流信息转换为HEX字符串
/// </summary>
public static string DumpBytes(byte[] bytes)
{
return DumpBytes(bytes, , bytes.Length);
} /// <summary>
/// 将字节流信息转换为HEX字符串
/// </summary>
public static string DumpBytes(byte[] bytes, int offset, int len)
{
StringBuilder buf = new StringBuilder();
for(int i = ;i < len;i++)
{
if (i == || i % == )
buf.AppendLine(); buf.Append(ByteToHex(bytes[i + offset]));
buf.Append(' ');
}
buf.AppendLine();
return buf.ToString();
} /// <summary>
/// 计算字节块的模256校验和
/// </summary>
public static byte SumBytes(byte[] bytes, int offset, int len)
{
int sum = ;
for(int i = ;i < len;i++)
{
sum += bytes[i + offset];
if (sum >= )
{
sum = sum % ;
}
}
return (byte)sum;
} /// <summary>
/// 计算字节块的模256双字节校验和(低位在前)
/// </summary>
public static byte[] Sum2Bytes(byte[] bytes, int offset, int len)
{
int sum = ;
for(int i = ;i < len;i++)
sum += bytes[i + offset];
return new byte[] { (byte)(sum % ), (byte)(sum / ) };
} /// <summary>
/// 计算字节块的异或校验和
/// </summary>
public static byte XorSumBytes(byte[] bytes, int offset, int len)
{
byte sum = bytes[ + offset];
for(int i = ;i < len;i++)
{
sum = (byte)(sum ^ bytes[i + offset]);
}
return sum;
} /// <summary>
/// 计算字节块的异或校验和
/// </summary>
public static byte XorSumBytes(byte[] bytes)
{
return XorSumBytes(bytes, , bytes.Length);
} /// <summary>
/// 比较两个字节块是否相等。相等返回true否则false
/// </summary>
public static bool CompareBytes(byte[] bytes1, int offset1, byte[] bytes2, int offset2, int len)
{
for(int i = ;i < len;i++)
{
if (bytes1[i + offset1] != bytes2[i + offset2])
{
return false;
}
}
return true;
} /// <summary>
/// 将两个字符的hex转换为byte
/// </summary>
public static byte HexToByte(char[] hex, int offset)
{
byte result = ;
for(int i = ;i < ;i++)
{
char c = hex[i + offset];
byte b = ;
switch (c)
{
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
case '':
b = (byte)(c - '');
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
b = (byte)( + c - 'A');
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
b = (byte)( + c - 'a');
break;
}
if (i == )
{
b = (byte)(b * );
}
result += b;
} return result;
} /// <summary>
/// 将两个字符的hex转换为byte
/// </summary>
public static byte HexToByte(byte[] hex, int offset)
{
char[] chars = {(char)hex[offset], (char)hex[offset + ]};
return HexToByte(chars, );
} /// <summary>
/// 转换16进制字符串为字节数组
/// <param name="hex">有分隔或无分隔的16进制字符串,如“AB CD EF 12 34...”或“ABCDEF1234...”</param>
/// <param name="dot">任意分隔字符,但不能是16进制字符</param>
/// <returns>字节数组</returns>
/// </summary>
public static byte[] HexToByte(string hex, params char[] dot) {
char[] ca = new char[];
List<byte> list = new List<byte>();
for (int i = , n = ; i < hex.Length; i++) {
if (Array.IndexOf<char>(dot, hex[i]) >= ) {
continue;
} switch (++n) {
case :
ca[] = hex[i];
break; case :
ca[] = hex[i];
list.Add(ByteUtil.HexToByte(ca, ));
n = ;
break;
}
} return list.ToArray();
} /// <summary>
/// 将uint变量分解为四个字节。高位在前。
/// </summary>
public static void UintToBytes(uint i, byte[] bytes, int offset)
{
bytes[offset] = (byte)((i & 0xFF000000) >> );
bytes[offset + ] = (byte)((i & 0x00FF0000) >> );
bytes[offset + ] = (byte)((i & 0x0000FF00) >> );
bytes[offset + ] = (byte)(i & 0x000000FF);
} /// <summary>
/// 将uint变量分解为四个字节。高位在前。
/// </summary>
public static byte[] UintToBytes(uint i)
{
byte[] bytes = new byte[];
bytes[] = (byte)((i & 0xFF000000) >> );
bytes[] = (byte)((i & 0x00FF0000) >> );
bytes[] = (byte)((i & 0x0000FF00) >> );
bytes[] = (byte)(i & 0x000000FF);
return bytes;
} /// <summary>
/// 将int变量分解为四个字节。高位在前。
/// </summary>
public static byte[] IntToBytes(int i)
{
byte[] data = BitConverter.GetBytes(i);
Array.Reverse(data);
return data; //byte[] bytes = new byte[4];
//bytes[0] = (byte)((i & 0xFF000000) >> 24);
//bytes[1] = (byte)((i & 0x00FF0000) >> 16);
//bytes[2] = (byte)((i & 0x0000FF00) >> 8);
//bytes[3] = (byte)(i & 0x000000FF);
//return bytes;
} /// <summary>
/// 将四个字节合成为一个int
/// </summary>
public static uint BytesToUint(byte[] bytes, int offset)
{
uint a = ((uint)bytes[offset]) << ;
uint b = ((uint)bytes[offset + ]) << ;
uint c = ((uint)bytes[offset + ]) << ;
uint d = bytes[offset + ];
return a + b + c + d;
} /// <summary>
/// 将ulong变量分解为八个字节。高位在前。
/// </summary>
public static byte[] UlongToBytes(ulong i)
{
byte[] bytes = new byte[];
bytes[] = (byte)((i & 0xFF00000000000000) >> );
bytes[] = (byte)((i & 0x00FF000000000000) >> );
bytes[] = (byte)((i & 0x0000FF0000000000) >> );
bytes[] = (byte)((i & 0x000000FF00000000) >> );
bytes[] = (byte)((i & 0x00000000FF000000) >> );
bytes[] = (byte)((i & 0x0000000000FF0000) >> );
bytes[] = (byte)((i & 0x000000000000FF00) >> );
bytes[] = (byte)(i & 0x00000000000000FF);
return bytes;
} /// <summary>
/// 将八个字节合成为一个ulong
/// </summary>
public static ulong BytesToUlong(byte[] bytes, int offset)
{
ulong a = ((ulong)bytes[offset]) << ;
ulong b = ((ulong)bytes[offset + ]) << ;
ulong c = ((ulong)bytes[offset + ]) << ;
ulong d = ((ulong)bytes[offset + ]) << ;
ulong e = ((ulong)bytes[offset + ]) << ;
ulong f = ((ulong)bytes[offset + ]) << ;
ulong g = ((ulong)bytes[offset + ]) << ;
ulong h = bytes[offset + ];
return a + b + c + d + e + f + g + h;
} /// <summary>
/// 设置某个字节的指定位
/// </summary>
/// <param name="b">需要设置的字节</param>
/// <param name="pos">1-8, 1表示最低位, 8表示最高位</param>
/// <param name="on">true表示设置1, false表示设置0</param>
public static void ByteSetBit(ref byte b, int pos, bool on)
{
int temp = BITS[pos - ]; if (!on)
{
//取反
temp = temp ^ 0xFF;
} b = (byte)(on?(b | temp):(b & temp));
} /// <summary>
/// 判断某个byte的某个位是否为1
/// </summary>
/// <param name="pos">第几位,大于等于1</param>
public static bool ByteGetBit(byte b, int pos)
{
int temp = BITS[pos - ];
return (b & temp) != ;
} /// <summary>
/// 设置双比特值
/// </summary>
/// <param name="b">需要设置的字节</param>
/// <param name="low">低位, 1-7</param>
/// <param name="val">值,0-3</param>
/// <returns></returns>
public static void ByteSetBitPair(ref byte b, int low, int val)
{
if (low < || low > )
{
throw new ArgumentException(string.Format("无效的low值:{0}", low));
} switch(val)
{
case :
{
ByteUtil.ByteSetBit(ref b, low, false);
ByteUtil.ByteSetBit(ref b, low + , false);
break;
}
case :
{
ByteUtil.ByteSetBit(ref b, low, true);
ByteUtil.ByteSetBit(ref b, low + , false);
break;
}
case :
{
ByteUtil.ByteSetBit(ref b, low, false);
ByteUtil.ByteSetBit(ref b, low + , true);
break;
}
case :
{
ByteUtil.ByteSetBit(ref b, low, true);
ByteUtil.ByteSetBit(ref b, low + , true);
break;
}
default:
{
throw new ArgumentException(string.Format("无效的val值:{0}", val));
}
}
} /// <summary>
/// 读取双比特值
/// </summary>
/// <param name="b">需要读取的字节</param>
/// <param name="low">低位, 0-6</param>
/// <returns>0-3</returns>
public static byte ByteGetBitPair(byte b, int low)
{
if (low < || low > )
{
throw new ArgumentException(string.Format("无效的low值:{0}", low));
} int x = ;
x += ByteUtil.ByteGetBit(b, low)?:;
x += ByteUtil.ByteGetBit(b, low + )?:; return (byte)x;
} /// <summary>
/// 将short转换为两个字节
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static byte[] ShortToByte(short s)
{
return UshortToByte((ushort)s);
} /// <summary>
/// 将ushort转换为两个字节
/// </summary>
public static byte[] UshortToByte(ushort u)
{
return new byte[]{
(byte)(u >> ),
(byte)(u & 0x00FF)
};
} /// <summary>
/// 将两个字节转换为一个short
/// </summary>
public static short BytesToShort(byte[] data, int offset)
{
short a = data[offset], b = data[offset + ];
return (short)((a << ) + b);
} /// <summary>
/// 将两个字节转换为一个short
/// </summary>
public static ushort BytesToUshort(byte[] data, int offset)
{
ushort a = data[offset], b = data[offset + ];
return (ushort)((a << ) + b);
} /// <summary>
/// 将四个字节转换为int
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static int BytesToInt(byte[] data, int offset)
{
return (data[offset] << ) + (data[offset + ] << ) + (data[offset + ] << ) + data[offset + ];
} /// <summary>
/// 将guid字符串转换为等价的16维字节数组
/// </summary>
public static byte[] GuidToBytes(string s)
{
byte[] guid = new byte[];
char[] hex = s.Replace("-", string.Empty).Replace(" ", string.Empty).ToCharArray();
for (int i = ; i < ; i += )
{
guid[i / ] = ByteUtil.HexToByte(hex, i);
}
return guid;
} /// <summary>
/// CRC16校验表
/// </summary>
static ushort[] wCRCTalbeAbs = {0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400}; /// <summary>
/// 计数字节块的CRC16校验值
/// </summary>
public static int CRC16Bytes(byte[] bytes, int offset, int len)
{
int wCRC = 0xFFFF;
byte chChar; for (int i = offset; i < len; i++)
{
chChar = bytes[i];
wCRC = wCRCTalbeAbs[(chChar ^ wCRC) & ] ^ (wCRC >> );
wCRC = wCRCTalbeAbs[((chChar >> ) ^ wCRC) & ] ^ (wCRC >> );
} return wCRC;
} /// <summary>
/// 字节格式化,将字节转换为字节、KB、MB、GB显示
/// </summary>
/// <param name="bytes">字节数</param>
/// <returns>格式化后的字符串</returns>
public static string ByteFormater(long bytes)
{
const long KB = ;
const long MB = * ;
const long GB = * * ; if (bytes >= GB)
{
double result = bytes * 1.0 / GB;
return result.ToString("#,##0.0") + "GB";
}
if (bytes >= MB)
{
double result = bytes * 1.0 / MB;
return result.ToString("#,##0.0") + "MB";
}
if (bytes >= KB)
{
double result = bytes * 1.0 / KB;
return result.ToString("#,##0.0") + "KB";
}
return bytes.ToString("#,##0") + "字节";
}
}
byte数据的常用操作函数[转发]的更多相关文章
- R语言Data Frame数据框常用操作
Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...
- 转载:R语言Data Frame数据框常用操作
Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...
- Python--set常用操作函数
python提供了常用的数据结构,其中之一就是set,python中的set是不支持索引的.值不能重复.无需插入的容器. 简单记录下set常用的操作函数: 1.新建一个set: set("H ...
- JavaScript之数组的常用操作函数
js对数组的操作非常频繁,但是每次用到的时候都会被搞混,都需要去查相关API,感觉这样很浪费时间.为了加深印象,所以整理一下对数组的相关操作. 常用的函数 concat() 连接两个或更多的数组,并返 ...
- R语言︱基本函数、统计量、常用操作函数
先言:R语言常用界面操作 帮助:help(nnet) = ?nnet =??nnet 清除命令框中所有显示内容:Ctrl+L 清除R空间中内存变量:rm(list=ls()).gc() 获取或者设置当 ...
- [转]pymongo常用操作函数
pymongo 是 mongodb 的 python Driver Editor.记录下学习过程中感觉以后会常用多一些部分,以做参考. 1. 连接数据库 要使用pymongo最先应该做的事就是先连上运 ...
- pymongo 常用操作函数
pymongo 是 mongodb 的 python Driver Editor. 记录下学习过程中感觉以后会常用多一些部分,以做参考. 1. 连接数据库 要使用pymongo最先应该做的事就是先连上 ...
- 入门大数据---SparkSQL常用聚合函数
一.简单聚合 1.1 数据准备 // 需要导入 spark sql 内置的函数包 import org.apache.spark.sql.functions._ val spark = SparkSe ...
- MYSQL常用操作函数的封装
1.mysql常用函数封装文件:mysql.func.php <?php /** * 连接MYSQL函数 * @param string $host * @param string $usern ...
随机推荐
- 腾讯云>>云通信>>TLS后台API在mac上JAVA DEMO搭建
1.相关文档地址 2.相关demo代码 代码部分作了修改,使用了commons-io中的IOUtils.toString简化了io操作 public class Demo { public stati ...
- Word,PDF,PPT,TXT之间的转换方法
来源: 刘波的日志 一.把PPT转WORD形式的方法 1.利用"大纲"视图 打开PPT演示文稿,单击"大纲",在左侧"幻灯片/大纲”任务窗格的“大纲” ...
- 基本shell命令使用笔记
linux常用命令: (ls:列出目录内容) -a/-all 列出所有文件,包括隐藏文件 -l 使用长格式显示详细信息,包括rwx (mkdir:建立目录) -p/-parents 若要建立目录的上层 ...
- 锁相关知识 & mutex怎么实现的 & spinlock怎么用的 & 怎样避免死锁 & 内核同步机制 & 读写锁
spinlock在上一篇文章有提到:http://www.cnblogs.com/charlesblc/p/6254437.html 通过锁数据总线来实现. 而看了这篇文章说明:mutex内部也用到 ...
- ROS学习笔记(七)——节点
NEW 1 #打开新的终端,以后不再注释$ sudo apt-get install ros-<distro>-ros-tutorials #下载一个教学用的仿真器$ roscore #运 ...
- swagger for c# webapi
最近迷上了前后端分离的开发架构,工作中的项目几乎都采取这种模式,自己主要担任服务端RestFul风格的Webapi开发.那么问题来了,当前端开发人员找我要api说明文档的时候,曾一度非常可耻的冒出过w ...
- mmorpg手游中的战斗系统
目前的项目是一款mmorpg手游, 非常不幸的是,当前战斗系统的实现非常脆弱, 也毫无技巧可言.具体存在如下问题: 1.战斗层逻辑与自动战斗AI逻辑混在一起, 互相纠缠. 2.战斗层自身逻辑混乱不堪, ...
- python3 购物程序
要求: 一.启动程序后,选择是商家还是用户 1.选择商家用户 输入用户名,密码进入 选择增加商品及价格:格式: 商品名称 价格 选择编辑商品及价格:根据提示进行操作 2.选择用户 输入用户名,密码进 ...
- ftp put本地文件至ubuntu服务器报错
起因:我想把本地下载的安装包上传至服务器. 由于Mac的ftp图形化客户端还没找着合适的,就想着用命令也是一样的. 但是又进坑了. 下载能够正常运行: ftp> get 2.jpg /Users ...
- 几款极好的 JavaScript 文件上传插件
文件上传功能作为网页重要的组成部分,几乎无处不在,从简单的单个文件上传到复杂的批量上传.拖放上传,需要开发者花费大量的时间和精力去处理,以期实现好用的上传功能.这篇文章向大家推荐几款很棒的 JavaS ...