Question

I'm trying to isolate two bytes that are next to each other add them, but there seems to be an extra bit that sometimes shows up and I can't figure out how to get rid of it. It's throwing off the answer. The code is:

(acc & 0x00000000ff000000L) + ((acc << 8) & 0x00000000ff000000L);

and I'm getting results such as

0x0000000147000000

when it should be

0x0000000047000000

How can I get rid of the 1?

Edit: acc is a long. I'm try to add the 5th and 6th byte and then that value will go into a new long in the 5th byte position.

Was it helpful?

Solution

You need to mask the bits you want at the end, because the addition may carry a bit:

((acc & 0x00000000ff000000L) + ((acc << 8) & 0x00000000ff000000L)) & 0x00000000ff000000L;

I think this might be clearer if you broke it down a little:

acc&=0x00000000FFFF000000L; // isolate bytes 5 and 4
acc+=(acc<<8);              // add the two bytes (we'll strip bytes 6 & 4 next)
acc&=0x00000000FF00000000L; // reduce to byte 5 only

which happens to be one less bitwise opperation too.

OTHER TIPS

If I understand correctly, you want to get the value of the 5th and 6th byte, add them together, and store them in a new long that contains just that sum in the 5th byte. This would be done like this:

long 5thByte = acc & 0xff00000000 >>> 32;
long 6thByte = acc & 0xff0000000000 >>> 40;
long sum = 5thByte + 6thByte;
long longWithNewByte = sum << 32;

This will of course carryover to the 6th byte if the sum is higher than 255. To get rid of that carryover, you can use another mask.

long longWithNewByte &= 0xff00000000;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top