3

[EDIT]

I realized that unfortunately I oversimplified the question and the answers aren't really helping me, so I'm rephraseing it...

So, my situation I have a stream of incoming bytes (sample) in which the ONLY bit that is potentially set is the first one (0000 | 0001).

So, let's say I get a sequence of these that looks like this:

0000,000**0**,
0000,000**1**,
0000,000**0**,
0000,000**1**,
0000,000**0**,
0000,000**0**,
0000,000**0**,
0000,000**0**

I'm setting the relevant bit to bold to make it clearer as to what I'm actually collecting.

So, as these 'bits' arrive I need to sort them into something that looks like this: 0000,1010

I'm doing this by shifting the existing value >> 1 and then adding the incoming value shifted over by << 7

byte aggregateByte = 0;
//loop 8 times as incoming samples arrive...
aggregateByte = (aggregateByte >> 1) + incomingSample << 7

This (*should) produce the correct result.

HOWEVER because java doesn't have the notion of an signed/insigned, EVERY time I shift, because I'm starting on the left hand side, if the previous incoming bit was 1, java PRESERVES the 1 since it sees this as the sign bit and never allows it to reset back to 0.

So... what I need to do prior to adding my incoming bit is to flip the first bit in the existing byte to 0 and then the incoming bit will be set to whatever it needs to be set to.

Currently I'm doing this by setting a mask of 0x7F and &ing that against the byte.

So, my actual addition looks like this: ((aggregateByte >> 1) & 0x7F ) + incomingSample << 7

0x7F creates a mask that looks like this: 0111,111 So, when I & this against the existing value, it flips the last bit to 0.

I guess my question is "am I reinventing the wheel, and is there a better way to handle this, or will this reliably work and is a relatively efficient way to handle this process?"

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236

2 Answers2

4

Neither | nor & is for toggling bits. For that, you need to use ^. But 0x40 is indeed the correct value for flipping bit 6 ("7th" in your terms).

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
3

To flip bit 3:

 final int N = 3;
 b = (byte) (b ^ (1 << N));
fred02138
  • 3,323
  • 1
  • 14
  • 17