SlackStack
SlackStack

Reputation: 79

How do I make a bit mask that only masks certain parts (indices) of 32 bits?

I am currently working on a programming assignment in which I have to mask only a certain index of the whole 32-bit number(EX: If I take 8 4-bit numbers into my 32-bit integer, I would have 8 indices with 4 bits in each). I want to be able to print only part of the bits out of the whole 32 bits, which can be done with masking. If the bits were to only be in one place, I would not have a problem, for I would just create a mask that puts the 1s in a set place(EX: 00000000 00000000 00000000 00000001). However, I need to be able to shift the mask throughout only one index to print each bit (EX: I want to loop through the first index with my 0001 mask, shifting the 1 left every time, but I do not want to continue after the third bit of that index). I know that I need a loop to accomplish this; however, I am having a difficult time wrapping my head around how to complete this part of my assignment. Any tips, suggestions, or corrections would be appreciated. Also, I'm sorry if this was difficult to understand, but I could not find a better way to word it. Thanks.

Upvotes: 1

Views: 15707

Answers (1)

Serge
Serge

Reputation: 12344

first of all about representation. You need binary numbers to represent bits and masks. There are no binaries implemented directly in c/c++ languages at least before c++14. So, before c++14 you had to use hexadecimals or octals to represent your binaries, i.e.

0000 1111 == 0x0F
1111 1010 == 0xFA

since c++14 you can use

0b00001111;

Now, if you shift your binary mask left or right, you will have the following pictures

00001111 (OxF) << 2 ==> 00111100 (0x3C)
00001111 (0xF) >> 2 ==> 00000011 (0x03)

Now, supposedly you have an number in which you are interested in bits 4 to 7 (4 bits)

int bad = 0x0BAD; // == 0000 1011 1010 1101

you can create a mask as

int mask = 0x00F0; // == 0000 0000 1111 00000

and do bitwise and

int result = bad & mask; // ==> 0000 0000 1010 000 (0x00A0)

You will mask 4 bits in the middle of the word, but it will print as 0xA0. probably not what you would expect. To print it as 0xA you would need to shift the result 4 bits right: result >> 4. I prefer doing it in a bit different order, shifting the 'bad' first and then mask:

int result = (bad >> 4) & 0xF;

I hope the above will help you to understand bits.

Upvotes: 3

Related Questions