我觉得写改成String的不好吧,况且输入参数是unsigned long哦,即相当于Delphi里的Longword,我写成这样了,应该没错吧? 我在想有没有其他更好的方法,例如象C语言那样尽量使用指针。 (* Byte swap a long *) function byteswap(x:Longword):Longword; var cp,cp1,cp2,cp3:Longword; begin cp := x and $ff; cp1 := x shr 8 and $ff; cp2 := x shr 16 and $ff; cp3 := x shr 24 and $ff; x := cp shl 24 or cp1 shl 16 or cp2 shl 8 or cp3; Result := x; end;
westfly: 可C代码的意思不是简单的Swap(X)高低位交换啊
procedure ByteSwap(var X: Cardinal); var X_Map: array[0..3] of Byte absolute X; var Temp: Byte; begin Temp := X_Map[0]; X_Map[0] := X_Map[3]; X_Map[3] := Temp;
function Rev(const s : string) : string; var i : integer; begin SetLength(Result,Length(s)); for i := 1 to Length(s) do Result[(Length(s)-i)+1] := s[i]; end;
procedure ByteSwap(var X: Cardinal); var X_Map: array[0..3] of Byte absolute X; var Temp: Byte; begin Temp := X_Map[0]; X_Map[0] := X_Map[3]; X_Map[3] := Temp;
或者你调用汇编指令xchg来实现也可以。
我在想有没有其他更好的方法,例如象C语言那样尽量使用指针。
(* Byte swap a long *)
function byteswap(x:Longword):Longword;
var
cp,cp1,cp2,cp3:Longword;
begin
cp := x and $ff;
cp1 := x shr 8 and $ff;
cp2 := x shr 16 and $ff;
cp3 := x shr 24 and $ff; x := cp shl 24 or cp1 shl 16 or cp2 shl 8 or cp3; Result := x;
end;
可C代码的意思不是简单的Swap(X)高低位交换啊
var X_Map: array[0..3] of Byte absolute X;
var Temp: Byte;
begin
Temp := X_Map[0];
X_Map[0] := X_Map[3];
X_Map[3] := Temp;
Temp := X_Map[1];
X_Map[1] := X_Map[2];
X_Map[2] := Temp;
end;
var i : integer;
begin
SetLength(Result,Length(s));
for i := 1 to Length(s) do Result[(Length(s)-i)+1] := s[i];
end;
var X_Map: array[0..3] of Byte absolute X;
var Temp: Byte;
begin
Temp := X_Map[0];
X_Map[0] := X_Map[3];
X_Map[3] := Temp;
Temp := X_Map[1];
X_Map[1] := X_Map[2];
X_Map[2] := Temp;
end;
var Temp: Byte;p:pchar;
begin
p:=@x;
Temp := p[0];
p[0] := p[3];
p[3] := Temp;
Temp := p[1];
p[1] := p[2];
p[2] := Temp;
end;
a:=htonl(b);
y:= byteswap(x);
把X处理后的值给Y,后面可能还要用X,而你却把X给变了.
function byteswap(x: Cardinal ):Cardinal;
var
cp: PChar;
tmp: Char;
begin
cp := PChar(@x);
tmp := cp[3];
cp[3] := cp[0];
cp[0] := tmp;
tmp := cp[2];
cp[2] := cp[1];
cp[1] := tmp;
Result := x;
end;