x86 assembly: ADD/SUB/INC/DEC without overflow and branching -


in x86 asm, possible disallow overflowing when adding or subtracting without branching? example, when subtracting 0x02 0x01 set 0x00 rather 0xff.

i expect may impossible, i'm interested in answer more restricted form of question 0x01 added/subtracted. had idea goes (of being overflow flag):

dec eax add eax,of 

i don't know other architectures, i386 couldn't find opcodes since apparently flags can't interpreted integers , used in arithmetic operations. found solution work, lowest byte when higher byte unused:

dec ax sub al,ah xor ah,ah 

is there better way this, maybe 1 that's applicable more general cases?

you can use cmov (conditional mov) family of instructions on newer processors avoid branching in many cases, including example describe. these instructions behave regular mov if flag values set appropriately, or otherwise nothing.

see http://www.jaist.ac.jp/iscenter-new/mpc/altix/altixdata/opt/intel/vtune/doc/users_guide/mergedprojects/analyzer_ec/mergedprojects/reference_olh/mergedprojects/instructions/instruct32_hh/vc35.htm

however:

i had idea goes (of being overflow flag)

it's not overflow flag want; indicates value overflowed bounds representable using 2's complement (so 16-bit word value, if became less -32768 or greater 32767). appear using unsigned numbers (and want clamping 0), want carry flag.

you can use cmovc load new value if there carry (if result wrapped 0 0xff), instance.

sub ax, 1 xor bx, bx cmovc ax, bx 

this works when subtracting value. however, turns out, there simpler way if want decrement. can subtract 1, , add 0 + carry using instruction that:

sub ax, 1 adc ax, 0 

note can't use dec instruction substitute sub because dec not affect carry flag.

for going other way (addition), use sbb in place of adc (and of course add in place of sub). general case, can like:

add ax, 1 mov bx, 0ffffh cmovc ax, bx 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -