gpt4 book ai didi

C# 替换二进制文件中的 HEX

转载 作者:行者123 更新时间:2023-11-30 15:47:16 26 4
gpt4 key购买 nike

我有一个二进制文件,其中有一些应该更改的值。更确切地说,在文件的两部分,在开头,有两个十六进制值

66 73 69 6D 35 2E 36 39

应该改成什么

4D 53 57 49 4E 34 2E 31

我怎样才能尽可能快地执行此异步操作?我已经到了将整个文件读入 byte[] 数组的地步,但此类没有搜索或替换功能。

最佳答案

这是我编写的一种方法,您可以使用它来查找您要查找的字节在 byte[] 中的位置。

/// <summary>
/// Searches the current array for a specified subarray and returns the index
/// of the first occurrence, or -1 if not found.
/// </summary>
/// <param name="sourceArray">Array in which to search for the
/// subarray.</param>
/// <param name="findWhat">Subarray to search for.</param>
/// <param name="startIndex">Index in <paramref name="sourceArray"/> at which
/// to start searching.</param>
/// <param name="sourceLength">Maximum length of the source array to search.
/// The greatest index that can be returned is this minus the length of
/// <paramref name="findWhat"/>.</param>
public static int IndexOfSubarray<T>(this T[] sourceArray, T[] findWhat,
int startIndex, int sourceLength) where T : IEquatable<T>
{
if (sourceArray == null)
throw new ArgumentNullException("sourceArray");
if (findWhat == null)
throw new ArgumentNullException("findWhat");
if (startIndex < 0 || startIndex > sourceArray.Length)
throw new ArgumentOutOfRangeException();
var maxIndex = sourceLength - findWhat.Length;
for (int i = startIndex; i <= maxIndex; i++)
{
if (sourceArray.SubarrayEquals(i, findWhat, 0, findWhat.Length))
return i;
}
return -1;
}

/// <summary>Determines whether the two arrays contain the same content in the
/// specified location.</summary>
public static bool SubarrayEquals<T>(this T[] sourceArray,
int sourceStartIndex, T[] otherArray, int otherStartIndex, int length)
where T : IEquatable<T>
{
if (sourceArray == null)
throw new ArgumentNullException("sourceArray");
if (otherArray == null)
throw new ArgumentNullException("otherArray");
if (sourceStartIndex < 0 || length < 0 || otherStartIndex < 0 ||
sourceStartIndex + length > sourceArray.Length ||
otherStartIndex + length > otherArray.Length)
throw new ArgumentOutOfRangeException();

for (int i = 0; i < length; i++)
{
if (!sourceArray[sourceStartIndex + i]
.Equals(otherArray[otherStartIndex + i]))
return false;
}
return true;
}

关于C# 替换二进制文件中的 HEX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com