1. /// <summary>
  2. /// 本类提供了对byte数据的常用操作函数
  3. /// </summary>
  4. public class ByteUtil
  5. {
  6. private static char[] HEX_CHARS = {'','','','','','','','','','','A','B','C','D','E','F'};
  7. private static byte[] BITS = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
  8.  
  9. /// <summary>
  10. /// 将字节数组转换为HEX形式的字符串, 使用指定的间隔符
  11. /// </summary>
  12. public static string ByteToHex(byte[] buf, string separator)
  13. {
  14. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  15. for(int i = ;i < buf.Length;i++)
  16. {
  17. if (i > )
  18. {
  19. sb.Append(separator);
  20. }
  21. sb.Append(HEX_CHARS[buf[i] >> ]).Append(HEX_CHARS[buf[i] & 0x0F]);
  22. }
  23. return sb.ToString();
  24. }
  25.  
  26. /// <summary>
  27. /// 将字节数组转换为HEX形式的字符串, 使用指定的间隔符
  28. /// </summary>
  29. public static string ByteToHex(byte[] buf, char c)
  30. {
  31. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  32. for(int i = ;i < buf.Length;i++)
  33. {
  34. if (i > )
  35. {
  36. sb.Append(c);
  37. }
  38. sb.Append(HEX_CHARS[buf[i] >> ]).Append(HEX_CHARS[buf[i] & 0x0F]);
  39. }
  40. return sb.ToString();
  41. }
  42.  
  43. /// <summary>
  44. /// 判断字节数组前几位是否符合一定规则
  45. /// </summary>
  46. /// <param name="data">需要判断的字节数组</param>
  47. /// <param name="pattern">匹配规则</param>
  48. /// <returns>如果匹配返回true</returns>
  49. public static bool IsMatch(byte[] data, params byte[] pattern)
  50. {
  51. if (data == null || data.Length < pattern.Length)
  52. return false;
  53.  
  54. for(int i = ;i < pattern.Length;i++)
  55. {
  56. if (data[i] != pattern[i])
  57. return false;
  58. }
  59. return true;
  60. }
  61.  
  62. /// <summary>
  63. /// 判断指定字节是否为列举的某个值
  64. /// </summary>
  65. /// <param name="value">需要判断的值</param>
  66. /// <param name="choice">可能值</param>
  67. /// <returns>如果与任一个可能值相等则返回true</returns>
  68. public static bool IsMatch(byte value, params byte[] choice)
  69. {
  70. if (choice == null || choice.Length == )
  71. return false;
  72.  
  73. foreach(byte item in choice)
  74. {
  75. if (item == value)
  76. return true;
  77. }
  78. return false;
  79. }
  80.  
  81. /// <summary>
  82. /// 将字节数组转换为HEX形式的字符串, 没有间隔符
  83. /// </summary>
  84. public static string ByteToHex(byte[] buf)
  85. {
  86. return ByteToHex(buf, string.Empty);
  87. }
  88.  
  89. /// <summary>
  90. /// 将字节数组转换为HEX形式的字符串
  91. /// 转换后的字符串长度为字节数组长度的两倍
  92. /// 如: 1, 2 转换为 0102
  93. /// </summary>
  94. public static string ByteToHex(byte b)
  95. {
  96. return string.Empty + HEX_CHARS[b >> ] + HEX_CHARS[b & 0x0F];
  97. }
  98.  
  99. /// <summary>
  100. /// 将字节流信息转换为HEX字符串
  101. /// </summary>
  102. public static string DumpBytes(byte[] bytes)
  103. {
  104. return DumpBytes(bytes, , bytes.Length);
  105. }
  106.  
  107. /// <summary>
  108. /// 将字节流信息转换为HEX字符串
  109. /// </summary>
  110. public static string DumpBytes(byte[] bytes, int offset, int len)
  111. {
  112. StringBuilder buf = new StringBuilder();
  113. for(int i = ;i < len;i++)
  114. {
  115. if (i == || i % == )
  116. buf.AppendLine();
  117.  
  118. buf.Append(ByteToHex(bytes[i + offset]));
  119. buf.Append(' ');
  120. }
  121. buf.AppendLine();
  122. return buf.ToString();
  123. }
  124.  
  125. /// <summary>
  126. /// 计算字节块的模256校验和
  127. /// </summary>
  128. public static byte SumBytes(byte[] bytes, int offset, int len)
  129. {
  130. int sum = ;
  131. for(int i = ;i < len;i++)
  132. {
  133. sum += bytes[i + offset];
  134. if (sum >= )
  135. {
  136. sum = sum % ;
  137. }
  138. }
  139. return (byte)sum;
  140. }
  141.  
  142. /// <summary>
  143. /// 计算字节块的模256双字节校验和(低位在前)
  144. /// </summary>
  145. public static byte[] Sum2Bytes(byte[] bytes, int offset, int len)
  146. {
  147. int sum = ;
  148. for(int i = ;i < len;i++)
  149. sum += bytes[i + offset];
  150. return new byte[] { (byte)(sum % ), (byte)(sum / ) };
  151. }
  152.  
  153. /// <summary>
  154. /// 计算字节块的异或校验和
  155. /// </summary>
  156. public static byte XorSumBytes(byte[] bytes, int offset, int len)
  157. {
  158. byte sum = bytes[ + offset];
  159. for(int i = ;i < len;i++)
  160. {
  161. sum = (byte)(sum ^ bytes[i + offset]);
  162. }
  163. return sum;
  164. }
  165.  
  166. /// <summary>
  167. /// 计算字节块的异或校验和
  168. /// </summary>
  169. public static byte XorSumBytes(byte[] bytes)
  170. {
  171. return XorSumBytes(bytes, , bytes.Length);
  172. }
  173.  
  174. /// <summary>
  175. /// 比较两个字节块是否相等。相等返回true否则false
  176. /// </summary>
  177. public static bool CompareBytes(byte[] bytes1, int offset1, byte[] bytes2, int offset2, int len)
  178. {
  179. for(int i = ;i < len;i++)
  180. {
  181. if (bytes1[i + offset1] != bytes2[i + offset2])
  182. {
  183. return false;
  184. }
  185. }
  186. return true;
  187. }
  188.  
  189. /// <summary>
  190. /// 将两个字符的hex转换为byte
  191. /// </summary>
  192. public static byte HexToByte(char[] hex, int offset)
  193. {
  194. byte result = ;
  195. for(int i = ;i < ;i++)
  196. {
  197. char c = hex[i + offset];
  198. byte b = ;
  199. switch (c)
  200. {
  201. case '':
  202. case '':
  203. case '':
  204. case '':
  205. case '':
  206. case '':
  207. case '':
  208. case '':
  209. case '':
  210. case '':
  211. b = (byte)(c - '');
  212. break;
  213. case 'A':
  214. case 'B':
  215. case 'C':
  216. case 'D':
  217. case 'E':
  218. case 'F':
  219. b = (byte)( + c - 'A');
  220. break;
  221. case 'a':
  222. case 'b':
  223. case 'c':
  224. case 'd':
  225. case 'e':
  226. case 'f':
  227. b = (byte)( + c - 'a');
  228. break;
  229. }
  230. if (i == )
  231. {
  232. b = (byte)(b * );
  233. }
  234. result += b;
  235. }
  236.  
  237. return result;
  238. }
  239.  
  240. /// <summary>
  241. /// 将两个字符的hex转换为byte
  242. /// </summary>
  243. public static byte HexToByte(byte[] hex, int offset)
  244. {
  245. char[] chars = {(char)hex[offset], (char)hex[offset + ]};
  246. return HexToByte(chars, );
  247. }
  248.  
  249. /// <summary>
  250. /// 转换16进制字符串为字节数组
  251. /// <param name="hex">有分隔或无分隔的16进制字符串,如“AB CD EF 12 34...”或“ABCDEF1234...”</param>
  252. /// <param name="dot">任意分隔字符,但不能是16进制字符</param>
  253. /// <returns>字节数组</returns>
  254. /// </summary>
  255. public static byte[] HexToByte(string hex, params char[] dot) {
  256. char[] ca = new char[];
  257. List<byte> list = new List<byte>();
  258. for (int i = , n = ; i < hex.Length; i++) {
  259. if (Array.IndexOf<char>(dot, hex[i]) >= ) {
  260. continue;
  261. }
  262.  
  263. switch (++n) {
  264. case :
  265. ca[] = hex[i];
  266. break;
  267.  
  268. case :
  269. ca[] = hex[i];
  270. list.Add(ByteUtil.HexToByte(ca, ));
  271. n = ;
  272. break;
  273. }
  274. }
  275.  
  276. return list.ToArray();
  277. }
  278.  
  279. /// <summary>
  280. /// 将uint变量分解为四个字节。高位在前。
  281. /// </summary>
  282. public static void UintToBytes(uint i, byte[] bytes, int offset)
  283. {
  284. bytes[offset] = (byte)((i & 0xFF000000) >> );
  285. bytes[offset + ] = (byte)((i & 0x00FF0000) >> );
  286. bytes[offset + ] = (byte)((i & 0x0000FF00) >> );
  287. bytes[offset + ] = (byte)(i & 0x000000FF);
  288. }
  289.  
  290. /// <summary>
  291. /// 将uint变量分解为四个字节。高位在前。
  292. /// </summary>
  293. public static byte[] UintToBytes(uint i)
  294. {
  295. byte[] bytes = new byte[];
  296. bytes[] = (byte)((i & 0xFF000000) >> );
  297. bytes[] = (byte)((i & 0x00FF0000) >> );
  298. bytes[] = (byte)((i & 0x0000FF00) >> );
  299. bytes[] = (byte)(i & 0x000000FF);
  300. return bytes;
  301. }
  302.  
  303. /// <summary>
  304. /// 将int变量分解为四个字节。高位在前。
  305. /// </summary>
  306. public static byte[] IntToBytes(int i)
  307. {
  308. byte[] data = BitConverter.GetBytes(i);
  309. Array.Reverse(data);
  310. return data;
  311.  
  312. //byte[] bytes = new byte[4];
  313. //bytes[0] = (byte)((i & 0xFF000000) >> 24);
  314. //bytes[1] = (byte)((i & 0x00FF0000) >> 16);
  315. //bytes[2] = (byte)((i & 0x0000FF00) >> 8);
  316. //bytes[3] = (byte)(i & 0x000000FF);
  317. //return bytes;
  318. }
  319.  
  320. /// <summary>
  321. /// 将四个字节合成为一个int
  322. /// </summary>
  323. public static uint BytesToUint(byte[] bytes, int offset)
  324. {
  325. uint a = ((uint)bytes[offset]) << ;
  326. uint b = ((uint)bytes[offset + ]) << ;
  327. uint c = ((uint)bytes[offset + ]) << ;
  328. uint d = bytes[offset + ];
  329. return a + b + c + d;
  330. }
  331.  
  332. /// <summary>
  333. /// 将ulong变量分解为八个字节。高位在前。
  334. /// </summary>
  335. public static byte[] UlongToBytes(ulong i)
  336. {
  337. byte[] bytes = new byte[];
  338. bytes[] = (byte)((i & 0xFF00000000000000) >> );
  339. bytes[] = (byte)((i & 0x00FF000000000000) >> );
  340. bytes[] = (byte)((i & 0x0000FF0000000000) >> );
  341. bytes[] = (byte)((i & 0x000000FF00000000) >> );
  342. bytes[] = (byte)((i & 0x00000000FF000000) >> );
  343. bytes[] = (byte)((i & 0x0000000000FF0000) >> );
  344. bytes[] = (byte)((i & 0x000000000000FF00) >> );
  345. bytes[] = (byte)(i & 0x00000000000000FF);
  346. return bytes;
  347. }
  348.  
  349. /// <summary>
  350. /// 将八个字节合成为一个ulong
  351. /// </summary>
  352. public static ulong BytesToUlong(byte[] bytes, int offset)
  353. {
  354. ulong a = ((ulong)bytes[offset]) << ;
  355. ulong b = ((ulong)bytes[offset + ]) << ;
  356. ulong c = ((ulong)bytes[offset + ]) << ;
  357. ulong d = ((ulong)bytes[offset + ]) << ;
  358. ulong e = ((ulong)bytes[offset + ]) << ;
  359. ulong f = ((ulong)bytes[offset + ]) << ;
  360. ulong g = ((ulong)bytes[offset + ]) << ;
  361. ulong h = bytes[offset + ];
  362. return a + b + c + d + e + f + g + h;
  363. }
  364.  
  365. /// <summary>
  366. /// 设置某个字节的指定位
  367. /// </summary>
  368. /// <param name="b">需要设置的字节</param>
  369. /// <param name="pos">1-8, 1表示最低位, 8表示最高位</param>
  370. /// <param name="on">true表示设置1, false表示设置0</param>
  371. public static void ByteSetBit(ref byte b, int pos, bool on)
  372. {
  373. int temp = BITS[pos - ];
  374.  
  375. if (!on)
  376. {
  377. //取反
  378. temp = temp ^ 0xFF;
  379. }
  380.  
  381. b = (byte)(on?(b | temp):(b & temp));
  382. }
  383.  
  384. /// <summary>
  385. /// 判断某个byte的某个位是否为1
  386. /// </summary>
  387. /// <param name="pos">第几位,大于等于1</param>
  388. public static bool ByteGetBit(byte b, int pos)
  389. {
  390. int temp = BITS[pos - ];
  391. return (b & temp) != ;
  392. }
  393.  
  394. /// <summary>
  395. /// 设置双比特值
  396. /// </summary>
  397. /// <param name="b">需要设置的字节</param>
  398. /// <param name="low">低位, 1-7</param>
  399. /// <param name="val">值,0-3</param>
  400. /// <returns></returns>
  401. public static void ByteSetBitPair(ref byte b, int low, int val)
  402. {
  403. if (low < || low > )
  404. {
  405. throw new ArgumentException(string.Format("无效的low值:{0}", low));
  406. }
  407.  
  408. switch(val)
  409. {
  410. case :
  411. {
  412. ByteUtil.ByteSetBit(ref b, low, false);
  413. ByteUtil.ByteSetBit(ref b, low + , false);
  414. break;
  415. }
  416. case :
  417. {
  418. ByteUtil.ByteSetBit(ref b, low, true);
  419. ByteUtil.ByteSetBit(ref b, low + , false);
  420. break;
  421. }
  422. case :
  423. {
  424. ByteUtil.ByteSetBit(ref b, low, false);
  425. ByteUtil.ByteSetBit(ref b, low + , true);
  426. break;
  427. }
  428. case :
  429. {
  430. ByteUtil.ByteSetBit(ref b, low, true);
  431. ByteUtil.ByteSetBit(ref b, low + , true);
  432. break;
  433. }
  434. default:
  435. {
  436. throw new ArgumentException(string.Format("无效的val值:{0}", val));
  437. }
  438. }
  439. }
  440.  
  441. /// <summary>
  442. /// 读取双比特值
  443. /// </summary>
  444. /// <param name="b">需要读取的字节</param>
  445. /// <param name="low">低位, 0-6</param>
  446. /// <returns>0-3</returns>
  447. public static byte ByteGetBitPair(byte b, int low)
  448. {
  449. if (low < || low > )
  450. {
  451. throw new ArgumentException(string.Format("无效的low值:{0}", low));
  452. }
  453.  
  454. int x = ;
  455. x += ByteUtil.ByteGetBit(b, low)?:;
  456. x += ByteUtil.ByteGetBit(b, low + )?:;
  457.  
  458. return (byte)x;
  459. }
  460.  
  461. /// <summary>
  462. /// 将short转换为两个字节
  463. /// </summary>
  464. /// <param name="s"></param>
  465. /// <returns></returns>
  466. public static byte[] ShortToByte(short s)
  467. {
  468. return UshortToByte((ushort)s);
  469. }
  470.  
  471. /// <summary>
  472. /// 将ushort转换为两个字节
  473. /// </summary>
  474. public static byte[] UshortToByte(ushort u)
  475. {
  476. return new byte[]{
  477. (byte)(u >> ),
  478. (byte)(u & 0x00FF)
  479. };
  480. }
  481.  
  482. /// <summary>
  483. /// 将两个字节转换为一个short
  484. /// </summary>
  485. public static short BytesToShort(byte[] data, int offset)
  486. {
  487. short a = data[offset], b = data[offset + ];
  488. return (short)((a << ) + b);
  489. }
  490.  
  491. /// <summary>
  492. /// 将两个字节转换为一个short
  493. /// </summary>
  494. public static ushort BytesToUshort(byte[] data, int offset)
  495. {
  496. ushort a = data[offset], b = data[offset + ];
  497. return (ushort)((a << ) + b);
  498. }
  499.  
  500. /// <summary>
  501. /// 将四个字节转换为int
  502. /// </summary>
  503. /// <param name="data"></param>
  504. /// <param name="offset"></param>
  505. /// <returns></returns>
  506. public static int BytesToInt(byte[] data, int offset)
  507. {
  508. return (data[offset] << ) + (data[offset + ] << ) + (data[offset + ] << ) + data[offset + ];
  509. }
  510.  
  511. /// <summary>
  512. /// 将guid字符串转换为等价的16维字节数组
  513. /// </summary>
  514. public static byte[] GuidToBytes(string s)
  515. {
  516. byte[] guid = new byte[];
  517. char[] hex = s.Replace("-", string.Empty).Replace(" ", string.Empty).ToCharArray();
  518. for (int i = ; i < ; i += )
  519. {
  520. guid[i / ] = ByteUtil.HexToByte(hex, i);
  521. }
  522. return guid;
  523. }
  524.  
  525. /// <summary>
  526. /// CRC16校验表
  527. /// </summary>
  528. static ushort[] wCRCTalbeAbs = {0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400};
  529.  
  530. /// <summary>
  531. /// 计数字节块的CRC16校验值
  532. /// </summary>
  533. public static int CRC16Bytes(byte[] bytes, int offset, int len)
  534. {
  535. int wCRC = 0xFFFF;
  536. byte chChar;
  537.  
  538. for (int i = offset; i < len; i++)
  539. {
  540. chChar = bytes[i];
  541. wCRC = wCRCTalbeAbs[(chChar ^ wCRC) & ] ^ (wCRC >> );
  542. wCRC = wCRCTalbeAbs[((chChar >> ) ^ wCRC) & ] ^ (wCRC >> );
  543. }
  544.  
  545. return wCRC;
  546. }
  547.  
  548. /// <summary>
  549. /// 字节格式化,将字节转换为字节、KB、MB、GB显示
  550. /// </summary>
  551. /// <param name="bytes">字节数</param>
  552. /// <returns>格式化后的字符串</returns>
  553. public static string ByteFormater(long bytes)
  554. {
  555. const long KB = ;
  556. const long MB = * ;
  557. const long GB = * * ;
  558.  
  559. if (bytes >= GB)
  560. {
  561. double result = bytes * 1.0 / GB;
  562. return result.ToString("#,##0.0") + "GB";
  563. }
  564. if (bytes >= MB)
  565. {
  566. double result = bytes * 1.0 / MB;
  567. return result.ToString("#,##0.0") + "MB";
  568. }
  569. if (bytes >= KB)
  570. {
  571. double result = bytes * 1.0 / KB;
  572. return result.ToString("#,##0.0") + "KB";
  573. }
  574. return bytes.ToString("#,##0") + "字节";
  575. }
  576. }

byte数据的常用操作函数[转发]的更多相关文章

  1. R语言Data Frame数据框常用操作

    Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...

  2. 转载:R语言Data Frame数据框常用操作

    Data Frame一般被翻译为数据框,感觉就像是R中的表,由行和列组成,与Matrix不同的是,每个列可以是不同的数据类型,而Matrix是必须相同的. Data Frame每一列有列名,每一行也可 ...

  3. Python--set常用操作函数

    python提供了常用的数据结构,其中之一就是set,python中的set是不支持索引的.值不能重复.无需插入的容器. 简单记录下set常用的操作函数: 1.新建一个set: set("H ...

  4. JavaScript之数组的常用操作函数

    js对数组的操作非常频繁,但是每次用到的时候都会被搞混,都需要去查相关API,感觉这样很浪费时间.为了加深印象,所以整理一下对数组的相关操作. 常用的函数 concat() 连接两个或更多的数组,并返 ...

  5. R语言︱基本函数、统计量、常用操作函数

    先言:R语言常用界面操作 帮助:help(nnet) = ?nnet =??nnet 清除命令框中所有显示内容:Ctrl+L 清除R空间中内存变量:rm(list=ls()).gc() 获取或者设置当 ...

  6. [转]pymongo常用操作函数

    pymongo 是 mongodb 的 python Driver Editor.记录下学习过程中感觉以后会常用多一些部分,以做参考. 1. 连接数据库 要使用pymongo最先应该做的事就是先连上运 ...

  7. pymongo 常用操作函数

    pymongo 是 mongodb 的 python Driver Editor. 记录下学习过程中感觉以后会常用多一些部分,以做参考. 1. 连接数据库 要使用pymongo最先应该做的事就是先连上 ...

  8. 入门大数据---SparkSQL常用聚合函数

    一.简单聚合 1.1 数据准备 // 需要导入 spark sql 内置的函数包 import org.apache.spark.sql.functions._ val spark = SparkSe ...

  9. MYSQL常用操作函数的封装

    1.mysql常用函数封装文件:mysql.func.php <?php /** * 连接MYSQL函数 * @param string $host * @param string $usern ...

随机推荐

  1. Sublime Text 3插件安装

    自动安装: 1.通过快捷键 ctrl+` 或者 View > Show Console 菜单打开控制台 2.粘贴对应版本的代码后回车安装 适用于 Sublime Text 3: import   ...

  2. md语法之行内代码和代码片

    md语法之行内代码和代码片 比如说要在行内写上一句或者半句代码(代码的意思就是某种脚本语言), 用撇号围起来就可以了. 比如: import pandas as pd 写代码片(单独的一块脚本语言)的 ...

  3. iOS9 3DTouch开发

    在iOS 9中,新iPhone将第三维度添加到了用户界面. 用户现在可以用力摁下主屏按钮来快速调出应用提供的功能菜单. 在应用中,用户现在可以用力摁下视图以查看更多内容的预览并且快速访问一些功能. 想 ...

  4. Image放大缩小在放进Imageview

    // 拿到要缩小放大的Bitmap obitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_launcher) ...

  5. Michael Schatz - 序列比对课程

    Michael Schatz - Cold Spring Harbor Laboratory 最近在研究 BWA mem 序列比对算法,直接去看论文,看不懂,论文就3页,太精简了,好多背景知识都不了解 ...

  6. MySQL 日期时间相关函数整理

    -- 为日期增加一个时间间隔:date_add() SELECT NOW(); YEAR); MONTH); DAY); HOUR); MINUTE); SECOND); MICROSECOND); ...

  7. Vs2010在C#类文件头部添加文件注释的方法

    步骤: 1.VS2010 中找到(安装盘符以C盘为例) 32位操作系统路径:C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Item ...

  8. Android中View类OnClickListener和DialogInterface类OnClickListener冲突解决办法

    Android中View类OnClickListener和DialogInterface类OnClickListener冲突解决办法 如下面所示,同时导入这两个,会提示其中一个与另一个产生冲突. 1i ...

  9. jQuery滚动数字

    <ul class="dateList"> <li class="one"> <p class="titleName&q ...

  10. java连接数据库步骤

    一.加载JDBC驱动程序 Class.forName(driver) ; 如果直接是上面的代码运行,一定会报错.找不到驱动类java.lang.ClassNotFoundException: com. ...