![]() The bit located at the extreme right of variable b.Īs a reminder, b >= 1 is equivalent to b /= 2 If so we set bit 1 on r with | and move it just 1 bit to the left by We first check if b as a bit on the extreme right with (b & 1) Probably the most logical, consists in rotating the byte while applying a mask on the first bit (n & 1): unsigned char reverse_bits(unsigned char b)Īs the length of an unsigner char is 1 byte, which is equal to 8 bits, it means we will scan each bit while (byte_len-) There are many ways to reverse bits depending on what you mean the "simplest way". Std::cout << "bit 2 is " << (flags.test(2) ? "on\n" : "off\n") įlags ^= (mask1 | mask2) // flip bits 1 and 2įlags |= (mask1 | mask2) // turn bits 1 and 2 on ![]() Therefore, we can define bit masks using hexadecimal like this: constexpr std::uint8_t mask0 // 8 bits in size means room for 8 flags In the end, only the non-masked parts (the parts you want painted) get painted.Ī bit mask essentially performs the same function for bits - the bit mask blocks the bitwise operators from touching bits we don’t want modified, and allows access to the ones we do want modified. Then when you paint, the masking tape blocks the paint from reaching anything you don’t want painted. You might buy some masking tape and apply it to the glass and any other parts you don’t want painted. ![]() If you’re not careful, you risk painting not only the window frame, but also the glass itself. Instead they work with bit masks.Ī bit mask is a predefined set of bits that is used to select which specific bits will be modified by subsequent operations.Ĭonsider a real-life case where you want to paint a window frame. Unfortunately, the bitwise operators don’t know how to work with bit positions. turn them on or off), we need some way to identify the specific bits we want to manipulate. ![]() ![]() In order to manipulate individual bits (e.g. Now that we understand how they function, let’s take a look at how they’re more commonly used. In the previous lesson on bitwise operators ( O.2 - Bitwise operators), we discussed how the various bitwise operators apply logical operators to each bit within the operands. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |