EncodeHelper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace WWPipeLine.Commons
  6. {
  7. /// <summary>
  8. /// 编码转换类
  9. /// </summary>
  10. public class EncodeHelper
  11. {
  12. private EncodeHelper()
  13. {
  14. }
  15. #region 判断文件流是否为UTF8字符集
  16. /// <summary>
  17. /// 判断文件流是否为UTF8字符集
  18. /// </summary>
  19. /// <param name="sbInputStream">文件流</param>
  20. /// <returns>判断结果</returns>
  21. public static bool IsUTF8(FileStream sbInputStream)
  22. {
  23. int i;
  24. byte cOctets; // octets to go in this UTF-8 encoded character
  25. byte chr;
  26. bool bAllAscii = true;
  27. long iLen = sbInputStream.Length;
  28. cOctets = 0;
  29. for (i = 0; i < iLen; i++)
  30. {
  31. chr = (byte)sbInputStream.ReadByte();
  32. if ((chr & 0x80) != 0) bAllAscii = false;
  33. if (cOctets == 0)
  34. {
  35. if (chr >= 0x80)
  36. {
  37. do
  38. {
  39. chr <<= 1;
  40. cOctets++;
  41. }
  42. while ((chr & 0x80) != 0);
  43. cOctets--;
  44. if (cOctets == 0) return false;
  45. }
  46. }
  47. else
  48. {
  49. if ((chr & 0xC0) != 0x80)
  50. {
  51. return false;
  52. }
  53. cOctets--;
  54. }
  55. }
  56. if (cOctets > 0)
  57. {
  58. return false;
  59. }
  60. if (bAllAscii)
  61. {
  62. return false;
  63. }
  64. return true;
  65. }
  66. #endregion 判断文件流是否为UTF8字符集
  67. #region GB2312转换成UTF-8
  68. /// <summary>
  69. /// 将GB2312转换成UTF-8
  70. /// </summary>
  71. /// <param name="content"></param>
  72. /// <returns></returns>
  73. public static string GB2312ToUTF8(string content)
  74. {
  75. byte[] _byteData = GetDefaultByte(content);
  76. return Encoding.UTF8.GetString(_byteData);
  77. }
  78. #endregion GB2312转换成UTF-8
  79. #region 将字符串转换默认的Byte数组
  80. /// <summary>
  81. /// 将字符串转换默认的Byte数组
  82. /// </summary>
  83. /// <param name="content"></param>
  84. /// <returns></returns>
  85. public static byte[] GetDefaultByte(string content)
  86. {
  87. return Encoding.Default.GetBytes(content);
  88. }
  89. #endregion 将字符串转换默认的Byte数组
  90. #region 文件转化为Base64
  91. /// <summary>
  92. /// 文件转化为Base64
  93. /// </summary>
  94. /// <param name="path">文件路径</param>
  95. /// <returns>Base64</returns>
  96. public string FileToBase64String(string path)
  97. {
  98. FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
  99. byte[] buffer = new byte[fileStream.Length];
  100. fileStream.Read(buffer, 0, (int)fileStream.Length);
  101. fileStream.Close();
  102. fileStream.Dispose();
  103. MemoryStream memory = new MemoryStream(buffer);
  104. string base64 = Convert.ToBase64String(memory.ToArray());
  105. memory.Close();
  106. memory.Dispose();
  107. return base64;
  108. }
  109. #endregion 文件转化为Base64
  110. #region 图象转化为Base64
  111. /// <summary>
  112. /// 图象转化为Base64
  113. /// </summary>
  114. /// <param name="image">图象路径</param>
  115. /// <param name="format">图象格式</param>
  116. /// <returns>Base64</returns>
  117. //public string ImageToBase64String(Image image, ImageFormat format)
  118. //{
  119. // MemoryStream memory = new MemoryStream();
  120. // image.Save(memory, image.RawFormat);
  121. // string base64 = Convert.ToBase64String(memory.ToArray());
  122. // memory.Close();
  123. // memory.Dispose();
  124. // return base64;
  125. //}
  126. #endregion 图象转化为Base64
  127. #region Base64转化为图象
  128. /// <summary>
  129. /// Base64转化为图象
  130. /// </summary>
  131. /// <param name="base64">Base64</param>
  132. /// <returns>图象</returns>
  133. //public Image ImageFromBase64String(string base64)
  134. //{
  135. // MemoryStream memory = new MemoryStream(Convert.FromBase64String(base64));
  136. // Image result = Image.FromStream(memory);
  137. // memory.Close();
  138. // memory.Dispose();
  139. // return result;
  140. //}
  141. #endregion Base64转化为图象
  142. #region 图标转化为Base64
  143. /// <summary>
  144. /// 图标转化为Base64
  145. /// </summary>
  146. /// <param name="image">图标</param>
  147. /// <returns>Base64</returns>
  148. //public string IconToBase64String(Icon image)
  149. //{
  150. // MemoryStream memory = new MemoryStream();
  151. // image.Save(memory);
  152. // string base64 = Convert.ToBase64String(memory.ToArray());
  153. // memory.Close();
  154. // memory.Dispose();
  155. // return base64;
  156. //}
  157. #endregion 图标转化为Base64
  158. #region Base64转化为图标
  159. /// <summary>
  160. /// Base64转化为图标
  161. /// </summary>
  162. /// <param name="base64">Base64</param>
  163. /// <returns>图标</returns>
  164. //public Icon IconFromBase64String(string base64)
  165. //{
  166. // MemoryStream memory = new MemoryStream(Convert.FromBase64String(base64));
  167. // Icon result = new Icon(memory);
  168. // memory.Close();
  169. // memory.Dispose();
  170. // return result;
  171. //}
  172. #endregion Base64转化为图标
  173. #region IP 协议采用统一的校验算法
  174. /// <summary>
  175. /// IP 协议采用统一的校验算法
  176. /// </summary>
  177. /// <param name="buffer">buffer数组为整个ip包数组,需要转换成UInt16[]</param>
  178. /// <param name="size">size为buffer数组的长度</param>
  179. /// <returns>结果为0则数据正确,不为0表示通讯出错</returns>
  180. public static UInt16 checksum(UInt16[] buffer, int size)
  181. {
  182. Int32 cksum = 0;
  183. int counter;
  184. counter = 0;
  185. while (size > 0)
  186. {
  187. UInt16 val = buffer[counter];
  188. cksum += Convert.ToInt32(buffer[counter]);
  189. counter += 1;
  190. size = -1;
  191. }
  192. cksum = (cksum >> 16) + (cksum & 0xffff);
  193. cksum += (cksum >> 16);
  194. return (UInt16)(~cksum);
  195. }
  196. #endregion IP 协议采用统一的校验算法
  197. #region 生成字符串的ascii代码
  198. /// <summary>
  199. /// 生成字符串的ascii代码
  200. /// </summary>
  201. /// <param name= "s_Chinese "> 中文字符串,可夹英文 </param>
  202. /// <returns> </returns>
  203. public static string Gen_ASCII(string s_Chinese)
  204. {
  205. string str = "";
  206. for (int i = 0; i < s_Chinese.Length; i++)
  207. {
  208. char ch = s_Chinese[i];
  209. if ((ch != '\r') && (ch != '\n'))
  210. {
  211. str = str + ((short)ch).ToString("X");
  212. }
  213. }
  214. return str;
  215. }
  216. /// <summary>
  217. /// 生成字符串的ascii代码
  218. /// </summary>
  219. /// <param name= "s_Chinese "> 中文字符串,可夹英文 </param>
  220. /// <returns> </returns>
  221. public static string Get_ASCII(string s_Chinese)
  222. {
  223. string str = "";
  224. byte[] array = Encoding.ASCII.GetBytes(s_Chinese);
  225. for (int i = 0; i < array.Length; i++)
  226. {
  227. int asciicode = (int)(array[i]);
  228. if (asciicode > 63)
  229. {
  230. asciicode -= 64;
  231. }
  232. else
  233. {
  234. asciicode += 64;
  235. }
  236. str += Convert.ToString(asciicode);
  237. }
  238. return str;
  239. }
  240. /// <summary>
  241. /// 生成ascii代码的字符串
  242. /// </summary>
  243. /// <param name= "ByteArray">ascii代码 { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 }</param>
  244. /// <returns> </returns>
  245. public static string Get_ASCII(byte[] ByteArray)
  246. {
  247. ASCIIEncoding AE = new ASCIIEncoding();
  248. string strAsc = AE.GetString(ByteArray);
  249. return strAsc;
  250. }
  251. #endregion 生成字符串的ascii代码
  252. #region 生成ascii代码的字符数组
  253. /// <summary>
  254. /// 生成ascii代码的字符数组
  255. /// </summary>
  256. /// <param name= "ByteArray">ascii代码 { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 }</param>
  257. /// <returns> </returns>
  258. public static char[] Gen_ASCII(byte[] ByteArray)
  259. {
  260. ASCIIEncoding AE = new ASCIIEncoding();
  261. char[] CharArray = AE.GetChars(ByteArray);
  262. return CharArray;
  263. }
  264. #endregion 生成ascii代码的字符数组
  265. #region 字节数组转16进制字符串
  266. /// <summary>
  267. /// 字节数组转16进制字符串
  268. /// </summary>
  269. /// <param name="bytes"></param>
  270. /// <returns></returns>
  271. public static string byteToHexStr(byte[] bytes)
  272. {
  273. string returnStr = "";
  274. if (bytes != null)
  275. {
  276. for (int i = 0; i < bytes.Length; i++)
  277. {
  278. returnStr += bytes[i].ToString("X2") + " ";
  279. }
  280. }
  281. return returnStr;
  282. }
  283. /// <summary>
  284. /// 字节数组转16进制字符串
  285. /// </summary>
  286. /// <param name="bytes"></param>
  287. /// <returns></returns>
  288. public static string byteToHexStrTrim(byte[] bytes)
  289. {
  290. string returnStr = "";
  291. if (bytes != null)
  292. {
  293. for (int i = 0; i < bytes.Length; i++)
  294. {
  295. returnStr += bytes[i].ToString("X2");
  296. }
  297. }
  298. return returnStr;
  299. }
  300. #endregion 字节数组转16进制字符串
  301. #region 字符串转16进制字节数组
  302. /// <summary>
  303. /// 字符串转16进制字节数组
  304. /// </summary>
  305. /// <param name="hexString"></param>
  306. /// <returns></returns>
  307. public static byte[] strToToHexByte(string hexString)
  308. {
  309. hexString = hexString.Replace(" ", "");
  310. if ((hexString.Length % 2) != 0)
  311. hexString += " ";
  312. byte[] returnBytes = new byte[hexString.Length / 2];
  313. for (int i = 0; i < returnBytes.Length; i++)
  314. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  315. return returnBytes;
  316. }
  317. #endregion 字符串转16进制字节数组
  318. #region 16进制字符串异或
  319. /// <summary>
  320. /// 16进制字符串异或
  321. /// </summary>
  322. /// <param name="hexString"></param>
  323. /// <returns></returns>
  324. public static string str16Xor(string hexString)
  325. {
  326. string returnStr = "";
  327. hexString = hexString.Replace(" ", "");
  328. if ((hexString.Length % 2) != 0)
  329. hexString += " ";
  330. byte XorByte = 0;
  331. for (int i = 0; i < hexString.Length / 2; i++)
  332. XorByte ^= Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  333. byte[] strAry = Encoding.ASCII.GetBytes(XorByte.ToString("X"));
  334. returnStr = EncodeHelper.byteToHexStr(strAry);
  335. return returnStr;
  336. }
  337. #endregion 16进制字符串异或
  338. #region 转全角\半角的函数
  339. /// <summary>
  340. /// 转全角的函数(SBC case)
  341. ///
  342. ///任意字符串
  343. ///全角字符串
  344. ///
  345. ///全角空格为12288,半角空格为32
  346. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  347. /// </summary>
  348. /// <param name="input">任意字符串</param>
  349. /// <returns></returns>
  350. public static String ToSBC(String input)
  351. {
  352. // 半角转全角:
  353. char[] c = input.ToCharArray();
  354. for (int i = 0; i < c.Length; i++)
  355. {
  356. if (c[i] == 32)
  357. {
  358. c[i] = (char)12288;
  359. continue;
  360. }
  361. if (c[i] < 127)
  362. c[i] = (char)(c[i] + 65248);
  363. }
  364. return new String(c);
  365. }
  366. /// <summary>
  367. ///
  368. /// 转半角的函数(DBC case)
  369. ///
  370. ///任意字符串
  371. ///半角字符串
  372. ///
  373. ///全角空格为12288,半角空格为32
  374. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  375. /// </summary>
  376. /// <param name="input"></param>
  377. /// <returns></returns>
  378. public static String ToDBC(String input)
  379. {
  380. char[] c = input.ToCharArray();
  381. for (int i = 0; i < c.Length; i++)
  382. {
  383. if (c[i] == 12288)
  384. {
  385. c[i] = (char)32;
  386. continue;
  387. }
  388. if (c[i] > 65280 && c[i] < 65375)
  389. c[i] = (char)(c[i] - 65248);
  390. }
  391. return new String(c);
  392. }
  393. #endregion 转全角\半角的函数
  394. #region 是否全角\半角
  395. /// <summary>
  396. /// 是否全角的函数(SBC case)
  397. ///
  398. ///任意字符串
  399. ///全角字符串
  400. ///
  401. ///全角空格为12288,半角空格为32
  402. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  403. /// </summary>
  404. /// <param name="input">任意字符串</param>
  405. /// <returns></returns>
  406. public static bool IsSBC(string input)
  407. {
  408. if (2 * input.Length == Encoding.Default.GetByteCount(input))
  409. {
  410. return true;
  411. }
  412. else
  413. {
  414. return false;
  415. }
  416. }
  417. /// <summary>
  418. /// 是否半角的函数(DBC case)
  419. ///
  420. ///任意字符串
  421. ///全角字符串
  422. ///
  423. ///全角空格为12288,半角空格为32
  424. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  425. /// </summary>
  426. /// <param name="input">任意字符串</param>
  427. /// <returns></returns>
  428. public static bool IsDBC(string input)
  429. {
  430. if (input.Length == Encoding.Default.GetByteCount(input))
  431. {
  432. return true;
  433. }
  434. else
  435. {
  436. return false;
  437. }
  438. }
  439. #endregion 是否全角\半角
  440. #region 转换Image到byte[] 数组
  441. ///// <summary>
  442. ///// 转换Image到byte[] 数组
  443. ///// </summary>
  444. ///// <param name="imageIn">Image</param>
  445. ///// <returns>byte[] 数组</returns>
  446. //public static byte[] imageToByteArray(System.Drawing.Image imageIn)
  447. //{
  448. // MemoryStream ms = new MemoryStream();
  449. // imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  450. // byte[] returnBuffer = new byte[ms.Length];
  451. // ms.Read(returnBuffer, 0, int.Parse(ms.Length.ToString()));
  452. // //清空和释放内存流
  453. // ms.Close();
  454. // ms.Dispose();
  455. // return returnBuffer;
  456. //}
  457. #endregion 转换Image到byte[] 数组
  458. #region 转换byte[]到Image
  459. ///// <summary>
  460. ///// 转换byte[]到Image
  461. ///// </summary>
  462. ///// <param name="imageIn">byte[] 数组</param>
  463. ///// <returns>Image</returns>
  464. //public static Image byteArrayToImage(byte[] byteArrayIn)
  465. //{
  466. // MemoryStream ms = new MemoryStream(byteArrayIn);
  467. // Image returnImage = Image.FromStream(ms);
  468. // ms.Close();
  469. // ms.Dispose();
  470. // return returnImage;
  471. //}
  472. #endregion 转换byte[]到Image
  473. #region 将字节数组转换成字符串
  474. /// <summary>
  475. /// 将字节数组转换成字符串
  476. /// </summary>
  477. /// <param name = "b">字节数组</param>
  478. /// <returns>返回转换后的字符串</returns>
  479. public static string byteToString(byte[] b)
  480. {
  481. Encoding enc = Encoding.GetEncoding("GB2312");
  482. string str = enc.GetString(b);
  483. str = str.Substring(0, str.IndexOf('\0') >= 0 ? str.IndexOf('\0') : str.Length);//去掉无用字符
  484. return str;
  485. }
  486. #endregion 将字节数组转换成字符串
  487. #region 编码方式转换
  488. public static string StringToBitString(string input)
  489. {
  490. return StringToBitString(input, Encoding.Default);
  491. }
  492. public static string StringToBitString(string input, Encoding encoding)
  493. {
  494. byte[] stringBytes = encoding.GetBytes(input);
  495. StringBuilder result = new StringBuilder(stringBytes.Length * 8);
  496. foreach (byte b in stringBytes)
  497. {
  498. for (int i = 128; i > 0; i /= 2)
  499. {
  500. result.Append(((b & i) == 0) ? 0 : 1);
  501. }
  502. }
  503. return result.ToString();
  504. }
  505. public static string BitStringToString(string input)
  506. {
  507. return BitStringToString(input, Encoding.Default);
  508. }
  509. public static string BitStringToString(string input, Encoding encoding)
  510. {
  511. List<byte> byteArray = new List<byte>();
  512. byte temp = 0;
  513. for (int i = 0, j = 0; i < input.Length; i++)
  514. {
  515. if (input[i] == '1') temp |= (byte)(1 << (8 - i % 8 - 1));
  516. if (++j == 8)
  517. {
  518. byteArray.Add(temp);
  519. temp = 0;
  520. j = 0;
  521. }
  522. }
  523. string result = new string(encoding.GetChars(byteArray.ToArray()));
  524. return result;
  525. }
  526. #endregion 编码方式转换
  527. #region int byte 互转
  528. /// <summary>
  529. /// byte 转int
  530. /// </summary>
  531. /// <param name="bytesData"></param>
  532. /// <returns></returns>
  533. public static int BytesToInt(byte[] bytesData)
  534. {
  535. int num = 0;
  536. for (int i = 0; i < bytesData.Length; i++)
  537. {
  538. num += bytesData[i] << (8 * i);
  539. }
  540. return num;
  541. }
  542. /// <summary>
  543. /// bytes转int
  544. /// </summary>
  545. /// <param name="bytesData">自己数据</param>
  546. /// <param name="offset">偏移量</param>
  547. /// <param name="length">字节长度最大为4最小为1,如果length 大于4或小于1 内部赋值为2</param>
  548. /// <returns>int值</returns>
  549. public static int BytesToInt(byte[] bytesData, int offset, int length = 4)
  550. {
  551. int num = 0;
  552. if (length < 1 || length > 4)
  553. {
  554. length = 2;
  555. }
  556. for (int i = 0; i < length; i++)
  557. {
  558. num += bytesData[i + offset] << (8 * i);
  559. }
  560. return num;
  561. }
  562. /// <summary>
  563. /// int转byte
  564. /// </summary>
  565. /// <param name="data"></param>
  566. /// <param name="length">字节长度最大为4最小为1,如果length 大于4或小于1 内部赋值为2</param>
  567. /// <returns></returns>
  568. public static byte[] IntToBytes(int data, int length = 4)
  569. {
  570. if (length < 1 || length > 4)
  571. {
  572. length = 2;
  573. }
  574. byte[] buffer = new byte[length];
  575. for (int i = 0; i < length; i++)
  576. {
  577. buffer[i] = (byte)(data >> (i * 8));
  578. }
  579. return buffer;
  580. }
  581. #endregion int byte 互转
  582. #region Color 转为short
  583. /// <summary>
  584. /// 将Color转为Short类型
  585. /// </summary>
  586. /// <param name="color"></param>
  587. /// <returns></returns>
  588. //public static short ColorToShort(Color color)
  589. //{
  590. // return (short)(((color.R & 0xf8) << 8)
  591. // | ((color.G & 0xfc) << 3)
  592. // | ((color.B & 0xf8) >> 3));//红高5,绿高6,蓝高5
  593. //}
  594. #endregion Color 转为short
  595. }
  596. }