1

I came across the following code to convert 16-bit numbers to 10-bit numbers and store it inside an integer. Could anyone maybe explain to me what exactly is happening with the AND 0x03?

// Convert the data to 10-bits    
    int xAccl = (((data[1] & 0x03) * 256) + data[0]);    
    if(xAccl > 511) {    
      xAccl -= 1024;  
    }

Link to where I got the code: https://www.instructables.com/id/Measurement-of-Acceleration-Using-ADXL345-and-Ardu/

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Take a random 16-bit value, and do the operations one by one *on paper*. See what you get at each step of the way. – Some programmer dude Oct 20 '18 at 14:29
  • `data[1] & 0x03` means to take the number in `data` at index 1 and compare the binary representation of it to the binary representation of the `0x03` (this is hex). See [this](https://stackoverflow.com/questions/4757447/understanding-the-behavior-of-a-single-ampersand-operator-on-integers) for how the `&` comparison works. – CodingYoshi Oct 20 '18 at 14:34
  • Also please don't spam with unrelated language tags. Judging from the context of the link its code from an Arduino project, which means it's C++. – Some programmer dude Oct 20 '18 at 14:36
  • Sorry about that, its code taken from an Arduino project yes, but my code is written in a combination of C, C++ and C# for the different aspects of the project, but will definitely keep that in mind, thanks again! – Zandré van Heerden Oct 20 '18 at 14:44

2 Answers2

1

The bitwise operator & will make a mask, so in this case, it voids the 6 highest bits of the integer.

Basically, this code does a modulo % 1024 (for unsigned values).

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
0

data[1] takes the 2nd byte; & 0x03 masks that byte with binary 11 - so: takes 2 bits; * 256 is the same as << 8 - i.e. pushes those 2 bits into the 9th and 10th positions; adding data[0] to data combines these two bytes (personally I'd have used |, not +).

So; xAccl is now the first 10 bits, using big-endian ordering.

The > 511 seems to be a sign check; essentially, it is saying "if the 10th bit is set, treat the entire thing as a negative integer as though we'd used 10-bit twos complement rules".

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900