Resetting or setting certain bits on a binary number.

2k Views Asked by At

Hi can someone please help me understand how to set or rest certain bits. i believe it is known as masking but unsure how to proceed. I would be grateful for any help with my studies. The question is:

Given numbers a) 01111001 and b) 10001010.

  1. What 8 bit binary number would you use to RESET bits 6 and bits 0 of number a) and what logical operation would you use?

  2. What 8 bit binary number would you use to SET bits 5 and bits 2 of number b) and what logical operation would you use?

2

There are 2 best solutions below

3
On BEST ANSWER

I assume:

  • reset means to set a bit to $0$
  • set means to set a bit to $1$
  • numbers are little endian

To reset a bit, you have to use the $AND$ operation with a mask where the affected bit is set to $0$ and all other bits are set to $1$:

    01111001
AND 11011110
------------
    01011000

To set a bit, you have to use the $OR$ operation with a mask where the affected bit is set to $1$ and all other bits are set to $0$:

   10001010
OR 00010010
-----------
   10011010
10
On

Consider the XOR-operation, or $\hat{\lor}$, given over the following truth table for two binary variables:

$$\begin{array}{|c|c|c|c|} \hline p& q& p\hat{\lor}q\\ \hline 0& 0& 0\\ \hline 0& 1& 1\\ \hline 1& 0& 1\\ \hline 1& 1& 0\\ \hline \end{array}$$

You may generalize this operations for strings bit-wise. Can you apply this operation here? How would you set or reset a bit in a string? Play around with this a little(seriously, this is the key to getting an intuition) before you check the hint:

1. $10000010$ 2. $00100100$

EDIT: Since you've seen my answer, I want to add something regarding the answer of Stanley F., which I did not want to talk about before to not "spoil the surprise":

You may of course approach this problem with almost any classical binary operation(or at least with every set which is functionally complete). However, the advantage of using the exclusive or is of course that

  1. It applies to setting and removing bits.
  2. The to-be-modified bits correspond in their position to the set-ones in the corresponding string.