Advertisement
JimPlayzFN

C# Hex Swapper

Nov 15th, 2023
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4.  
  5. class HexReplace
  6. {
  7. static void Main()
  8. {
  9. Console.WriteLine("Enter the path to the .ucas file:");
  10. string filePath = Console.ReadLine();
  11.  
  12. Console.WriteLine("Enter the hex value to replace:");
  13. string hexToReplace = Console.ReadLine();
  14.  
  15. Console.WriteLine("Enter the new hex value:");
  16. string newHexValue = Console.ReadLine();
  17.  
  18. if (hexToReplace.Length != newHexValue.Length)
  19. {
  20. Console.WriteLine("Error: The lengths of the hex values should be the same.");
  21. return;
  22. }
  23.  
  24. try
  25. {
  26. // Read the content of the file
  27. string fileContent = File.ReadAllText(filePath);
  28.  
  29. // Search and replace the hex value
  30. string updatedContent = ReplaceHexValue(fileContent, hexToReplace, newHexValue);
  31.  
  32. // Write the updated content back to the file
  33. File.WriteAllText(filePath, updatedContent);
  34.  
  35. Console.WriteLine("Hex value replaced successfully.");
  36. }
  37. catch (Exception ex)
  38. {
  39. Console.WriteLine($"An error occurred: {ex.Message}");
  40. }
  41. }
  42.  
  43. static string ReplaceHexValue(string input, string hexToReplace, string newHexValue)
  44. {
  45. // Convert hex strings to byte arrays
  46. byte[] hexBytesToReplace = StringToByteArray(hexToReplace);
  47. byte[] newHexBytes = StringToByteArray(newHexValue);
  48.  
  49. // Replace the hex value in the input string
  50. int index = input.IndexOf(hexBytesToReplace, StringComparison.OrdinalIgnoreCase);
  51. while (index != -1)
  52. {
  53. input = input.Remove(index, hexBytesToReplace.Length);
  54. input = input.Insert(index, ByteArrayToString(newHexBytes));
  55. index = input.IndexOf(hexBytesToReplace, index + newHexBytes.Length, StringComparison.OrdinalIgnoreCase);
  56. }
  57.  
  58. return input;
  59. }
  60.  
  61. static byte[] StringToByteArray(string hex)
  62. {
  63. return Enumerable.Range(0, hex.Length)
  64. .Where(x => x % 2 == 0)
  65. .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
  66. .ToArray();
  67. }
  68.  
  69. static string ByteArrayToString(byte[] byteArray)
  70. {
  71. StringBuilder hex = new StringBuilder(byteArray.Length * 2);
  72. foreach (byte b in byteArray)
  73. {
  74. hex.AppendFormat("{0:x2}", b);
  75. }
  76. return hex.ToString();
  77. }
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement