Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set or clear the first 3 bits using bitwise operations?

Lets say I have a number like 0x448. In binary this is 0100 0100 1000.

How do I set the bits 1, 2 and 3 to either all 0's or all 1's using bit-wise operations? When I say the first three, I'm counting the rightmost bit as the zero bit.

So, for example

Bits as 1's:

b12            b0 
  0100 0100 1110
            ^^^

Bits as 0's:

b12            b0
  0100 0100 0000
            ^^^

I'm guessing that to set them to 1's I use bit-wise OR with a mask of 14 (0x000e)? But if that is the case, how do I do something similar for clearing the bits?


Related:

  • How do you set, clear and toggle a single bit in C? (syntax varies, but the operations are the same)
like image 888
Mithrax Avatar asked Apr 15 '09 03:04

Mithrax


2 Answers

You have the bit setting correct: OR with the mask of the bits you want to set.

Bit clearing bits is very similar: AND with the ones-complement of the bits you want cleared.

Example: Word of 0x0448.

Settings bits 1, 2 and 3 would be Word OR 0x000e:

    0000 0100 0100 1000 = 0x0448
 OR 0000 0000 0000 1110 = 0x000e
    ---- ---- ---- ----
  = 0000 0100 0100 1110 = 0x044e

Clearing bits 1, 2 and 3 would be Word AND 0xfff1:

    0000 0100 0100 1000 = 0x0448
AND 1111 1111 1111 0001 = 0xfff1
    ---- ---- ---- ----
  = 0000 0100 0100 0000 = 0x0440

Elaborating on the ones-complement, the AND pattern for clearing is the logical NOT of the OR pattern for setting (each bit reveresed):

 OR 0000 0000 0000 1110 = 0x000e
AND 1111 1111 1111 0001 = 0xfff1

so you can use your favorite language NOT operation instead of having to figure out both values.

like image 85
staticsan Avatar answered Oct 14 '22 13:10

staticsan


Supposing you have a mask m with bits set to 1 for all the bits you want to set or clear, and 0 otherwise:

  • clear bits: x & (~m)
  • set bits: x | m
  • flip bits: x ^ m

If you are only interested in one bit, in position p (starting at 0), the mask is simple to express m = 1 << p

Note that I am using C-style conventions, where:

  • ~ is the 1-complement: ~10001010 = 01110101
  • & is the bitwise AND
  • | is the bitwise OR
  • ^ is the bitwise XOR
  • << is the left bit shift: 10001010 << 2 = 00101000
like image 20
Varkhan Avatar answered Oct 14 '22 13:10

Varkhan