0

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.

MNagy
  • 423
  • 7
  • 20

1 Answers1

1

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.

Community
  • 1
  • 1
AShelly
  • 34,686
  • 15
  • 91
  • 152
  • I really like the idea, but it doesn't seem to work in my case. Good to know that there are ideas for it other than my mess above, however. – MNagy Jun 16 '15 at 06:07
  • I don't know about about HLSL but if it's a Turing-complete language then obviously it would support things like `T = (S < A) ? 1 : 0` or `if (S < A) T = 1; else T = 0;` – phuclv Aug 19 '17 at 15:11