Let's say that A and B are my lower 32bit integers, and T is a 32bit integer that I want to represent the carry from adding A and B. I threw together some quick logic to get T:

T = (A >> 1) + (B >> 1);
T += A & B & 1;
T >>= 31;

It works, but I'm not a huge fan of the number of operations required to do this (3 right shifts, 2 adds, 2 ands). I'd really appreciate input from some bit-twiddling experts on how to make this cleaner/more efficient. Thanks!

For my current problem, I'm limited to what I can do in HLSL. I wouldn't mind SM4 and SM5 specific solutions, but I'm also open to something that would work in general.

1

There are 1 answers

2
AShelly On

Would the technique here work: Efficient 128-bit addition using carry flag?

S = A + B;
T = (S < A);

I am assuming a comparison results in 1 or 0 like in C. If not, add ?1:0 to the end of the statement.