替换字节数组中某些字节的最佳方法是什么?
例如,我有bytesFromServer = listener.Receive(ref groupEP);,我可以做到BitConverter.ToString(bytesFromServer)将其转换为可读格式,以返回一些东西
48 65 6c 6c 6f 20
74 68 65 72 65 20
68 65 6c 70 66 75
6c 20 70 65 6f 70
6c 65
Run Code Online (Sandbox Code Playgroud)
我想将"68 65 6c"中的内容替换成类似"68 00 00"的内容(仅作为示例).字节[]上没有.Replace().
是否有一种简单的方法将其转换回字节[]?
任何帮助赞赏.谢谢!
ren*_*ene 10
你可以对它进行编程....尝试这个开始...然而这不是强大而不是像代码一样的生产...要知道一个错误我没有完全测试这个...
public int FindBytes(byte[] src, byte[] find)
{
int index = -1;
int matchIndex = 0;
// handle the complete source array
for(int i=0; i<src.Length; i++)
{
if(src[i] == find[matchIndex])
{
if (matchIndex==(find.Length-1))
{
index = i - matchIndex;
break;
}
matchIndex++;
}
else if (src[i] == find[0])
{
matchIndex = 1;
}
else
{
matchIndex = 0;
}
}
return index;
}
public byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
{
byte[] dst = null;
int index = FindBytes(src, search);
if (index>=0)
{
dst = new byte[src.Length - search.Length + repl.Length];
// before found array
Buffer.BlockCopy(src,0,dst,0, index);
// repl copy
Buffer.BlockCopy(repl,0,dst,index,repl.Length);
// rest of src array
Buffer.BlockCopy(
src,
index+search.Length ,
dst,
index+repl.Length,
src.Length-(index+search.Length));
}
return dst;
}
Run Code Online (Sandbox Code Playgroud)
实现作为扩展方法
public void Replace(this byte[] src, byte[] search, byte[] repl)
{
ReplaceBytes(src, search, repl);
}
Run Code Online (Sandbox Code Playgroud)
使用常规方法:
ReplaceBytes(bytesfromServer,
new byte[] {0x75, 0x83 } ,
new byte[]{ 0x68, 0x65, 0x6c});
Run Code Online (Sandbox Code Playgroud)
扩展方法用法:
bytesfromServer.Replace(
new byte[] {0x75, 0x83 },
new byte[]{ 0x68, 0x65, 0x6c});
Run Code Online (Sandbox Code Playgroud)
改进 rene 的代码,我为它创建了一个 while 循环来替换所有出现的:
public static byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
{
byte[] dst = null;
byte[] temp = null;
int index = FindBytes(src, search);
while (index >= 0)
{
if (temp == null)
temp = src;
else
temp = dst;
dst = new byte[temp.Length - search.Length + repl.Length];
// before found array
Buffer.BlockCopy(temp, 0, dst, 0, index);
// repl copy
Buffer.BlockCopy(repl, 0, dst, index, repl.Length);
// rest of src array
Buffer.BlockCopy(
temp,
index + search.Length,
dst,
index + repl.Length,
temp.Length - (index + search.Length));
index = FindBytes(dst, search);
}
return dst;
}
Run Code Online (Sandbox Code Playgroud)
这种方法可以工作,但如果源字节太大,我更喜欢使用“窗口化”功能来逐块处理字节。否则会占用大量内存。