我有这个 C 代码:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
uint32_t xor160()
{
static uint32_t x = 123456789,
y = 362436069, z = 521288629,
w = 88675123, v = 5783321;
uint32_t t = (x^(x<<2)); x = y; y = z; z = w; w = v;
return v = (v^(v>>4))^(t^(t>>1));
}
int main(void)
{
size_t i;
printf("Xorshift160:");
for(i=0; i<10; ++i)
{
printf(" %"PRIu32, xor160());
}
printf("\n\n");
return 0;
}
结果:
393427209 1947109840 565829276 1006220149 971147905 1436324242
2800460115 1484058076 3823330032 1552000024
当我将其转换为 Delphi 时,它给出了不同的结果,从 i = 6
开始到结束。
type
TForm1= class(TForm)
lst1: TListBox;
function xor160() : UInt64;
public
{ Public declarations }
x, y, z, v, w : UInt64;
end;
function TForm_Improved.xor160() : UInt64;
var
t: UInt64;
begin
t := (x xor (x shl 2));
x := y; y := z; z := w; w := v;
v := (v xor (v shr 4)) xor (t xor (t shr 1));
Result := v;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
i : Integer;
begin
x := 123456789;
y := 362436069;
z := 521288629;
w := 88675123;
v := 5783321;
for i := 0 to 10 do
lst1.Items.Add(UIntToStr( xor160() ) );
end;
结果:
393427209 1947109840 565829276 1006220149 971147905 1436324242
4947943763 7523855836 5945647856 7601759256 1532068462
最佳答案
正如评论中所述,问题在于 C 代码执行 32 位算术,但您的 Delphi 代码执行 64 位算术。
该程序产生与 C 程序相同的输出:
program Project1;
{$APPTYPE CONSOLE}
var
x: Cardinal = 123456789;
y: Cardinal = 362436069;
z: Cardinal = 521288629;
w: Cardinal = 88675123;
v: Cardinal = 5783321;
function xor160: Cardinal;
var
t: Cardinal;
begin
t := x xor (x shl 2);
x := y;
y := z;
z := w;
w := v;
v := (v xor (v shr 4)) xor (t xor (t shr 1));
Result := v;
end;
procedure Main;
var
i: Integer;
begin
Writeln('Xorshift160:');
for i := 0 to 9 do
Writeln(xor160);
end;
begin
Main;
Readln;
end.
关于C代码在Delphi中返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921108/