如果我这样做
var a,b,c:cardinal; begin a:=$80000000; b:=$80000000; c:=a+b; end;
c将等于0,因为加法溢出.捕获这个溢出布尔值的最佳方法是什么? (a b
在汇编中,术语溢出通常是指有符号算术,意味着总和的符号与两个操作数的符号不同;对于无符号算术,术语Carry是优选的.
您可以使用纯粹的pascal中的Overflow(Carry)检查来实现添加:
// signed add - returns True if no overflow produced function SAdd(A,B: integer; out C: integer): Boolean; begin C:= A + B; Result:= (A xor B < 0) // operands have different signs or (C xor A >= 0); // sum has the same sign as operands end; // unsigned add - returns True if no carry produced function UAdd(A,B: Cardinal; out C: Cardinal): Boolean; begin C:= A + B; Result:= (C >= A); end;
装配中的相同功能 – Andreas解决方案的优化变体:
// Signed Add function SAdd(A,B: Integer; out C: Integer): Boolean; asm ADD EAX,EDX MOV [ECX],EAX SETNO AL end; // Unsigned Add function UAdd(A,B: Cardinal; out C: Cardinal): Boolean; asm ADD EAX,EAX SETNC AL end;
翻译自:https://stackoverflow.com/questions/6418423/delphi-read-overflow-flag
转载注明原文:Delphi读溢出标志