0

Good evening,

I am trying to correlate the required values to the values that needs to be sent to an I2C device, and I am having issues with the bit math and masking.

My range goes from -15 to 15, so does the range of the device. Example of required values

Here is what I am using to get to the required values, it seems to be working as far as I can tell. "number1" is the Power On value for that register.

  int number1 = 254;
  int number2 = 14;
  int number3;
  int number4;

  if (number2 <= 0) {
    number3 = number2 + 15;
  }
  else {
    number3 = (number2 ^ 15) | 16; // XOR 0b00001111 then Set bit 4
}

  number4 = (number1 & 0b11100000) + number3;

I am having an issue trying to figure out how to set/clear the 5 required bits in the register which is 8 bits, without affecting the 3 highest bits.

I think I have it, but it seems like such an inefficient way of doing it, is there a better way of doing that ?

Thanks,

DW

  • There's nothing wrong with the way you are clearing the bits. I usually see HEX literals in bitwise operations (would be `number4 = (number1 & 0xE0) + number3;` in your example), but it doesn't really matter. – Eran Mar 09 '15 at 02:32

1 Answers1

0

to clear the 5 LSB bits of an 8 bits value without affecting the 3 MSB bits,

number &= 0xE0;

to set the 5 LSB bits,

number |= 0x1F;
faljbour
  • 1,367
  • 2
  • 8
  • 15