-1

It's easy to to change +1 to -1 and 0 to 1 with an expression like:

value = (value ? 0 : 1) - value;

But that introduces a branch. Is there a bitwise way to perform the same expression?

mmnormyle
  • 763
  • 1
  • 8
  • 18
  • just use abs() function , or do like this : #define abs(x) (x-(x*2)) – Skiller Dz Apr 30 '19 at 22:38
  • You can certainly do 1-(value<<1) if you hate branches that much, but your compiler will presumably emit similar machine code in both cases – Chemistree Apr 30 '19 at 22:39
  • `But that introduces a branch` are you sure? Ternary operators often compile to a branchless output. But branching isn't inherently bad, sometimes it's better than conditional moves – phuclv May 01 '19 at 01:20
  • almost duplicate: [Get 1, 0, -1 as positive, zero, or negative for an integer with math only](https://stackoverflow.com/q/26635250/995714), [n is negative, positive or zero? return 1, 2, or 4](https://stackoverflow.com/q/9558550/995714), [Branchless code that maps zero, negative, and positive to 0, 1, 2](https://stackoverflow.com/q/1610836/995714) – phuclv May 01 '19 at 01:24
  • @user463035818 I think your simple solution is really the most elegant. Why don't you turn that into an answer so mmnormyle can select it? – phonetagger May 11 '19 at 19:07

2 Answers2

3

Sure you could use boring old math, but why not use something weirder:

const int map[] = { 1, -1 };

thus,
map[1] yields -1
map[0] yields 1

so you'd write:
value = map[value];
Cruz Jean
  • 2,761
  • 12
  • 16
2

value = 1 - 2*value; maps 0 to 1 and +1 to -1 as requested.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185