1

Sorry if this is a duplicate, I couldn't find exactly what I want.

I have the current value of a byte:

00110001 A

And I have to write another value:

10001001 B

but in the 2nd byte only some bits are relevant. The relevant bits are the ones with a one in this bit

11000000 C

The final byte will be B on the bits where C==1 and A on the bits where C==0. How can I do that with no if statements?

The answer is D 10110001

4
  • 2
    if is not a loop, it's kind of a branching statement. Anyway, are you looking for the bitwise AND operator? Commented Jul 16, 2013 at 14:27
  • There are no such thing as "if loops". You probably mean "if statements". Commented Jul 16, 2013 at 14:27
  • @JonathonReinhart may be he means: with no if and loop Commented Jul 16, 2013 at 14:32
  • Thank you all for your quick correct answers. Commented Jul 16, 2013 at 14:44

2 Answers 2

7

Mask and combine:

finalByte = (B & C) | (A & ~C); 

To break down how it works - the result of B & C is a byte containing all of the bits of B where bits of C are set (a normal masking operation). A & ~C yields a byte with all of the bits of A where bits of C are cleared - hence the ~ complement operation. The | combines the two into the final byte you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

5
(B & C) | (A & ~C) 

The first expression keeps only the bits of B where C is set; the second keeps only the bits of A where C is not set; and the logical or combines those two bit-sets to give the result you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.