Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring masks for bitwise operations

I'm new to low level operations like this, I'm hoping someone can point out the obvious mistake I must be making here.

//Input value - 00111100
//I want to get the value of the bits at indexes 1-3 i.e 0111.

byte mask = (byte)0x00001111; // This gives 17 not the 15 I'd expect 

byte shifted = (byte)(headerByte >> 3);
//shifted is 7 as expected

byte frameSizeValue = (byte)(shifted & mask); //Gives 1 not 7

It looks like the problem lies with the way the mask is defined, but I can't see how to fix it.

like image 874
Tristan Warner-Smith Avatar asked Nov 14 '11 15:11

Tristan Warner-Smith


People also ask

What is a mask in Bitwise manipulation?

In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word, etc. can be set either on or off, or inverted from on to off (or vice versa) in a single bitwise operation.

Which Bitwise operator is used for masking?

The logical bitwise XOR operator can be used with a mask to toggle a bit.

What is meant by bit masking in C?

Bit masking is simply the process of storing data truly as bits, as opposed to storing it as chars/ints/floats. It is incredibly useful for storing certain types of data compactly and efficiently.


1 Answers

First of all 0x00001111 is in hex, which is a larger number than 255 - 16^3 + 16^2 + 16 + 1 = 4369 and byte overflows. Look here how to represent binary numbers or just use shifted & 15.

like image 107
Petar Minchev Avatar answered Sep 24 '22 19:09

Petar Minchev