ByteUtil.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Globalization;
  2. namespace Admin.NET.Core;
  3. /// <summary>
  4. /// 字节数组操作扩展类
  5. /// </summary>
  6. public static class ByteUtil
  7. {
  8. internal static byte[] AsciiBytes(string s)
  9. {
  10. byte[] bytes = new byte[s.Length];
  11. for (int i = 0; i < s.Length; i++)
  12. {
  13. bytes[i] = (byte)s[i];
  14. }
  15. return bytes;
  16. }
  17. internal static byte[] HexToByteArray(this string hexString)
  18. {
  19. byte[] bytes = new byte[hexString.Length / 2];
  20. for (int i = 0; i < hexString.Length; i += 2)
  21. {
  22. string s = hexString.Substring(i, 2);
  23. bytes[i / 2] = byte.Parse(s, NumberStyles.HexNumber, null);
  24. }
  25. return bytes;
  26. }
  27. internal static string ByteArrayToHex(this byte[] bytes)
  28. {
  29. var builder = new StringBuilder(bytes.Length * 2);
  30. foreach (byte b in bytes)
  31. {
  32. builder.Append(b.ToString("X2"));
  33. }
  34. return builder.ToString();
  35. }
  36. internal static string ByteArrayToHex(this byte[] bytes, int len)
  37. {
  38. return ByteArrayToHex(bytes).Substring(0, len * 2);
  39. }
  40. internal static byte[] RepeatByte(byte b, int count)
  41. {
  42. byte[] value = new byte[count];
  43. for (int i = 0; i < count; i++)
  44. {
  45. value[i] = b;
  46. }
  47. return value;
  48. }
  49. internal static byte[] SubBytes(this byte[] bytes, int startIndex, int length)
  50. {
  51. byte[] res = new byte[length];
  52. Array.Copy(bytes, startIndex, res, 0, length);
  53. return res;
  54. }
  55. internal static byte[] XOR(this byte[] value)
  56. {
  57. byte[] res = new byte[value.Length];
  58. for (int i = 0; i < value.Length; i++)
  59. {
  60. res[i] ^= value[i];
  61. }
  62. return res;
  63. }
  64. internal static byte[] XOR(this byte[] valueA, byte[] valueB)
  65. {
  66. int len = valueA.Length;
  67. byte[] res = new byte[len];
  68. for (int i = 0; i < len; i++)
  69. {
  70. res[i] = (byte)(valueA[i] ^ valueB[i]);
  71. }
  72. return res;
  73. }
  74. }