C#替换字节字节[] [英] C# Replace bytes in Byte[]
问题描述
什么是替换字节数组??
What is the best way to replace some bytes in a byte array??
例如一些字节的最好方式,我有 bytesFromServer = listener.Receive(REF groupEP);
,我可以做 BitConverter.ToString(bytesFromServer)
将其转换为可读的格式返回线沿线的东西。
For instance i have bytesFromServer = listener.Receive(ref groupEP);
and i can do BitConverter.ToString(bytesFromServer)
to convert it into a readable format to return something along the lines of
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
我想更换里面的东西该制作68 65 6C,以类似68 00 00(只是作为例子)。没有上一个byte [] .Replace()。
I would like to replace something inside of that making "68 65 6c" to something like "68 00 00" (just as an example). There is not .Replace() on a byte[].
会不会有一种简单的方法是转换回一个byte []
Would there be an easy way to convert that back into a byte[]?
任何帮助表示赞赏。谢谢!
Any help appreciated. Thank you!
推荐答案
您可以设定让它....试试这个一开始......这不过是不稳健不生产类似的代码,但... beaware关闭接一个错误,我没有完全测试这个...
You could program it.... try this for a start... this is however not robust not production like code yet...beaware of off-by-one errors I didn't fully test this...
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
{
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;
}
实施作为一个扩展的方法
Implement as an extension method
public void Replace(this byte[] src, byte[] search, byte[] repl)
{
ReplaceBytes(src, search, repl);
}
使用正常的方法:
usage normal method:
ReplaceBytes(bytesfromServer,
new byte[] {0x75, 0x83 } ,
new byte[]{ 0x68, 0x65, 0x6c});
扩展方法用法:
Extension method usage:
bytesfromServer.Replace(
new byte[] {0x75, 0x83 },
new byte[]{ 0x68, 0x65, 0x6c});
这篇关于C#替换字节字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!