bitwise operator on half a byte C#

-1

I am working on a project which outputs to an odd circuit and need to invert half the byte I am sending. So for example, if I am sending the number 100 as a byte, it comes out in the chip as 01100100, nice and easy. The problem is that I need it to be 10010100, i.e. the first nibble is inverted. This is because of how the outputs of the chip work.

I have playing with the ~ command doing something like:

int b = a & 0x0000000F;

This inverts the second nibble. I can also invert the whole thing with:

int b = a & 0x000000FF;

But I want to get the first nibble of the byte and

int b = a & 0x000000F0;

doesn't give me the answer I am after.

Any suggestions?

c#
asked on Stack Overflow Feb 1, 2020 by PSHutch • edited Feb 1, 2020 by Twonky

2 Answers

1

To invert a bit, you xor (exclusive or) it.

So you have to do a ^ 0xF0;

answered on Stack Overflow Feb 1, 2020 by Holger
0

with shifting:

b = (byte) ((b & 0x0F) + (~(b >> 4)<<4));

without shifting:

b = (byte)((b & 0x0F) + ((~(b & 0xF0)) & 0xF0));

(not that shifting or not matters...)

answered on Stack Overflow Feb 1, 2020 by Holger Lembke • edited Feb 1, 2020 by Holger Lembke

User contributions licensed under CC BY-SA 3.0