bit manipulation - Saturating signed integer addition with only bitwise operators in C (HW) -
for homework assignment, have write function in c adds 2 signed integers, returns int_max if there positive overflow , int_min if there negative overflow. have follow strict restrictions in operators can use. integers in two's complement form, right shifts arithmetic, , integer size variable (i can find sizeof(int)<<3). can't use contitionals, loops, comparison operators, or casting. can use bitwise , logical operators, addition , subtraction, equality tests, , integer constants int_max , int_min.
i know overflow can detected if 2 inputs have same sign , result has different sign. i've gotten point have flag showing if equation did overflow. have no idea how there end product. have far:
int saturating_add(int x, int y){ int w = sizeof(int)<<3; int result = x+y; int signx = (x>>w-1)&0x01;//sign bit of x int signy = (y>>w-1)&0x01;//sign bit of y int resultsign = (result>>w-1)&0x01; //sign bit of result int canoverflow = ~(signx ^ signy); //if they're same sign, can overflow int didoverflow = (resultsign^signx)&canoverflow; //1 if input signs same , result sign different, 0 otherwise }
i'm trying follow answer shown @ bitwise saturated addition in c (hw), i'm stuck on part have fill integer same bit sign bit (1 goes 0111..11 , 0 goes 0000.00). have no idea "combination of shifts , ors" be.
i think misunderstood answer. should extend sign bit all of bits, including msb. can accomplished taking int holding sign bit, e.g. didoverflow
, , add 1 complement.
then find overflow value should returned in case there overflow. can done xoring int_max
extended signx
(or signy
, both work). let's call value overflow
. finally, alter overflow
, result
this:
overflow := (extended didoverflow) , overflow result := (not (extended didoverflow)) , result
now, after these assignments, if extended didoverflow
1...1, overflow
remain unchanged. result
, on other hand, equal 0.
but if didoverflow
0...0, opposite applies: overflow
0, while result
remains unchanged.
in first case (where didoverflow
1...1, signaling there overflow), overflow or result
equals overflow
. in second case (where have no overflow), overflow or result
equals result
. either way, overflow or result
give correct value.
Comments
Post a Comment