Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to flip one bit in a byte while preserving the rest?

[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?"

like image 453
Yevgeny Simkin Avatar asked Dec 12 '25 17:12

Yevgeny Simkin


1 Answers

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).

like image 172
Chris Jester-Young Avatar answered Dec 15 '25 08:12

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!