All,
First post. Hope to stick around.
I got an assignment yesterday dealing with bits and bytes and C. There's a variety of functions we have to write that replicate operators using bitwise operations. The one I'm stuck on (this time, anyway...) is one that accepts to integers and then returns 1 if the first is greater than the second.
We're only allowed to use bitwise operators along with + and !, and the code has to be straight line. No functions, loops, etc. No unsigned ints permitted.
Here's what I came up with so far:
This works fine in a lot of cases, but I think when I get to values like the negative max, the output is incorrect. I'm assuming it has to do with some kind of overflow on the addition, but I'm unsure of how to actually fix it without the use of conditionals.Code:int greaterThan(int first, int second){ // first > second means second - first is less than 0 // shift the sign bit and then compare it to 1 return (second + (~first +1)) >> 31 & 1; }
Thanks.



LinkBack URL
About LinkBacks




