# 2's complement only works in one direction with the LSM303DLHC

In java I have the code

public void readAccel()
{
int l, h;

l = i2c.read(0x28);
h = i2c.read(0x29);

int x = ((h) << 8) | (l);
System.out.println(x);
}


in java. The accelerometer I have connected is working and communicating over i2c, the problem being that the two's complement number that is generated only seems to work in one direction; when I turn he device to one side the values scale from 0-256, but past zero the value jumps to 4096-3840. What Am I doing wrong?

• Is it a 12-bit device? Are you sign-extending the high bits properly? – Brian Drummond Mar 8 '14 at 22:23

## 1 Answer

Are you sure it jumps to 4096 and not 4095?

In any case, the problem is that you're not properly converting the 12-bit result to the native Java int type. Try this:

int x = ((h) << 8) | (l);
if (x > 2047) {
x = x - 4096;
}


Any values that have the high bit (bit 11) set will be properly converted to negative integers. 4095 becomes -1, 4094 becomes -2, etc.

• Interestingly enough my accelerometer now says about 65,536 (2^16) when turned to the right. I scaled the numbers accordingly and it works great. – AlexG Mar 8 '14 at 23:02