Computer Science — Test Set & Clear in C++

Jake Cutter
Technology Hits
Published in
2 min readDec 29, 2021

When working with different numbers and shifting of bits there are three different functions that come in handy to change the value of your desired number. For instance, you can shift the bits left and right, as well as Mask a number of bits to determine the value of a single bit where you can set the value to a 1 or 0.

Photo by Nate Grant on Unsplash

What is a Mask?

A mask is when you cover over a number of bits in a number. In simpler terms, you shift bits to the right in order to determine a value of an individual bit.

Test:

The function of Test is to determine the value of a bit within a number. For instance, if you want to know the value of the 7th bit in the number 400, you can shift the bits over to the 7th bit and find its value by the example below.

Example:

bool BITSET::Test(int index) const

{

int which_set, which_bit;

which_set = index / 32;

which_bit = index % 32;

return((which_set >> which_bit) & 1);

}

Reasoning:

The set gets shifted by the number of bits and then is ANDed with a 1. If it is a 1 or 0 the value is not changed because all it is returning is the value from the 32-bit number. The which_bit value is %(modulo) is a remainder and will determine the bit from the index, which is your number input.

Set & Clear:

The function Set sets the value of the desired bit to 1. For instance, if you want to change the value of the number using code you can rearrange any bit by setting it to a zero or one. Clear sets the value of the desired bit to a 0.

Example:

void BITSET::Set(int index)

{

int which_set, which_bit;

which_set = index / 32;

which_bit = index % 32;

//Set

(1 << which_bit) | which_set)

Reasoning:

Our index is a total number of 32 bits. In order to set which bit we left shift the desired bit and then or it with the given set. The Set is a vector. Which we can expand or narrow to include the number of integers we have.

Example:

~(1 << which_bit) & index

Reasoning:

The above example is Clear. First, you NOT the desired bit with 1 and then AND it with your integer that you are trying to reach.

Citations:

Marz, Stephen. Professor. 2021

--

--