Posted By

tecnoplaga on 01/07/19


Tagged

hex byte


Versions (?)

Hex String To ByteList


 / Published in: C#
 

It is a small code that you create for a project, combierte small chains hex to bytes that return by a list of corresponding bytes.

  1. /// <summary>
  2. /// Convert the argument string into their Byte List
  3. /// </summary>
  4. /// <param name="HexString">A separated list of hex numbers strings</param>
  5. /// <returns>List<byte> representation of the bytes</returns>
  6. public static List<byte> HexStringToByteList(string HexString)
  7. {
  8. HexString = HexString.Replace("\r", "");
  9. HexString = HexString.Replace("\n", "");
  10. HexString = HexString.Replace(" ", "");
  11. if (HexString.ToLower().StartsWith("0x"))
  12. {
  13. HexString = HexString.Substring(2);
  14. }
  15. if (HexString.Length % 2 != 0)
  16. {
  17. HexString = string.Concat("0", HexString);
  18. }
  19. List<byte> nums = new List<byte>(HexString.Length / 2);
  20. int length = HexString.Length;
  21. byte num = 0;
  22. for (int i = 0; i < length; i = i + 2)
  23. {
  24. if (!byte.TryParse(HexString.Substring(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num))
  25. {
  26. throw new Exception("Strings passed into HexStringToByteList must be valid hex strings.Error at position: " + "\r\n" + i.ToString() + "\r\n" + HexString + "\r\n" + i);
  27. }
  28. nums.Add(num);
  29. }
  30. return nums;
  31. }

Report this snippet  

You need to login to post a comment.