user4332529
user4332529

Reputation:

How to perform bitwise operations on 16bit numbers (Arduino)

I'm working on an Arduino powered Tetris game. To keep track of the pieces that have fallen and become fixed I have an array of bytes

byte theGrid[] = {   
B00000000,
B00000000,  
B00000000,
B00000000,
B00000000,
...

This works great when the well is only 8 LEDs wide, but I need it to be 16 wide. Is there a way to perform bitwise operations on a 16 bit number, like a short? I tried just declaring theGrid as a short, but I'm getting this error no matter what I do.

tetris:62: error: 'B0000000000000000' was not declared in this scope

Upvotes: 2

Views: 2821

Answers (1)

deviantfan
deviantfan

Reputation: 11434

...leading 'B' only works with 8 bit values (0 to 255)...

from http://arduino.cc/en/pmwiki.php?n=Reference/IntegerConstants

Just use hexadecimal notation, ie. 0x0000 for 2 bytes.
0x signals that it is hex, and every digit (0123456789ABCDEF) replaces 4 bit.

Instead of bitRead and bitSet, you can use following code;
The variable is x and the bit number i, with i=0 is the right-most bit, 1 the next ...):

//set bit to 1
x |= 1<<i;
//set bit to 0
x &= ~(1<<i);
//check if bit is set
if(x & (1<<i))  

Eg. x &= ~(1<<3); sets a value B11111111 (in binary representation) to B11110111,
that is 0xff to 0xf7. Btw., x &= ~(1<<3); is equivalent to x &= ~8;

Upvotes: 2

Related Questions