0

I want to use 2bits to switch on and off parts of a mathematical statement in a loop. Kinda like:

Result[i] = someMath*bits[0] + someMath*bits[1]

(bits[n] refers to index n, not a value of n)

Using them as flags but then in each loop I then want to increment them more as a binary encoded value:

bits++

So with each iteration the 2bits will cycle through 00,01,10,11,00,01 ...

Searching I found bitfields but I don't see an increment or array like way to access the elements.

Any ideas appreciated.

If it has to be 8bits, that's fine, the lowest two bits will still follow the pattern I'm after ;)

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Lamar Latrell
  • 1,669
  • 13
  • 28

1 Answers1

1
Result[i] = someMath*(bits&1) + someMath*((bits&2)>>1)
King King
  • 61,710
  • 16
  • 105
  • 130
JoseH
  • 86
  • 3
  • '&' is logic AND? And '>>' is shift right once? What type is bits in thus case? How is it initialised? Thanks for your help, I'm newish to actual code implementation, spend more time thinking about than doing, bad habit! Also, if I wanted to access an element directly, like the nth bit, how does that work in this case? – Lamar Latrell Sep 02 '13 at 10:49
  • & is the bitwise and operand in C#. >> N shifts N bits to right then: "(bits & 1)" give you access to the '0' bit (or first) and "(bits & 2) >> 1" give you access to the '1' bit (or second) also "(bits & N) >> N-1" give you access to the 'N-1' bit (or Nth) – JoseH Sep 02 '13 at 11:14
  • Correction Error: "(bits & N) >> N-1" give you access to the 'N-1' bit (or Nth) Correct: "(bits & (1 << N-1)) >> N-1" give you access to the 'N-1' bit (or Nth) – JoseH Sep 13 '13 at 14:30