是否有任何“Pos”函数来查找字节?
问题描述:
var
FileBuff: TBytes;
Pattern: TBytes;
begin
FileBuff := filetobytes(filename);
Result := CompareMem(@Pattern[0], @FileBuff[0], Length(Pattern));
end;
有什么功能,如是否有任何“Pos”函数来查找字节?
Result := Pos(@Pattern[0], @FileBuff[0]);
答
我觉得这个做的:
function BytePos(const Pattern: TBytes; const Buffer: PByte; const BufLen: cardinal): PByte;
var
PatternLength: cardinal;
i: cardinal;
j: cardinal;
OK: boolean;
begin
result := nil;
PatternLength := length(Pattern);
if PatternLength > BufLen then Exit;
if PatternLength = 0 then Exit(Buffer);
for i := 0 to BufLen - PatternLength do
if PByte(Buffer + i)^ = Pattern[0] then
begin
OK := true;
for j := 1 to PatternLength - 1 do
if PByte(Buffer + i + j)^ <> Pattern[j] then
begin
OK := false;
break
end;
if OK then
Exit(Buffer + i);
end;
end;
答
写你自己的。当只查找一个字节时,不能进行优化,所以你会发现任何实现基本上都会做同样的事情。
写在浏览器中:
function BytePos(Pattern:Byte; Buffer:PByte; BufferSize:Integer): Integer;
var i:Integer;
begin
for i:=0 to BufferSize-1 do
if Buffer[i] = Pattern then
begin
Result := i;
Exit;
end;
Result := -1;
end;
+1
我觉得@user想多字节模式的能力 – 2011-02-10 16:25:40
pos是二进制安全的,ANSIChar类型的数组喂养它,瞧,工程 – 2011-02-10 16:25:28
您可能也有兴趣在一个StringReplace功能字节:http://stackoverflow.com/questions/3106139/binary-version-of-stringreplace – 2011-02-10 16:52:12