Is there a reason why you are translating one bit position to another? It looks like keysHeld() is already returning a bit per key. Can’t you just do the following?
amount = keysHeld();
The only difference is keysHeld() can return more than one bit set and “amount” in your code can only have one bit set.
If you want to isolate one bit from all the set bits returned by keysHeld(), you can do this:
int rawBits = keysHeld();
int amount = rawBits & ~(rawBits ^ -rawBits);
Or is keysHeld() returning more than one byte (e.g. 16-bit) and you are trying to compress it into one byte? If so you may do the following:
int rawBits = keysHeld();
byte amount = 0;
if (rawBits & KEY_A) amount |= 0x01;
if (rawBits & KEY_B) amount |= 0x02;
if (rawBits & KEY_Y) amount |= 0x04;
if (rawBits & KEY_X) amount |= 0x08;
if (rawBits & KEY_L) amount |= 0x10;
if (rawBits & KEY_R) amount |= 0x20;
if (rawBits & KEY_START) amount |= 0x40;
if (rawBits & KEY_SELECT) amount |= 0x80;
Just curious, these looks like xbox controller buttons, what are you trying to do?
Well one way you could do it is with a for loop, but that would only really be efficient if the bit masks are consecutive. I only know Java, so I might get the C++ syntax wrong, but here is what it might look like:
int keys = keysHeld();
byte packedKeys = 0;
for (int i = 0; i < 8; i++) {
if (keys & (1 << i)) packedKeys |= 1 << i;
}
That would pack the values of the keys, but only if the bit masks were all in a line. You could also start the i variable at the first mask if it isn’t zero. I have the same question as mikets though. Why do you even need to do this if keysHeld() already returns the key values? It seems redundant to me.