2

So I know I can bit shift a mask of 0xFFFFFFFF by say 8 for example to get 0xFFFFFF00 & it with an address and get everything but the last 8 bits, but I would like to go the other way so I can grab the bottom end of an address with a mask like 0x000000FF, however bit shifting right wont work obviously. Any ideas?

Here is the code for the first type bit shift I mentioned.

public int Block_tag(int address, int block_size, int max_address) { int bit_shift = (int)Math.Log(block_size, 2); int bit_mask = max_address << bit_shift; return (address & bit_mask); } 

I could do it by hand with about 12 "If" statements but that isn't very clean.

Thanks!

2
  • Why do you need to shift? Just use the literal mask: address & 0x000000FF Commented Apr 1, 2013 at 4:17
  • Well I would like to shift the address of all F's so I can use the method modularly without having to hard code every shift. Commented Apr 1, 2013 at 4:22

2 Answers 2

1

To simply invert the mask use the ~ operator

int not_mask = ~bit_mask; 

For example, ~0xFFFFFF00 == 0x000000FF.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I didn't know that's how that operator was used. Works like a charm thanks!
0

You can right shift it by (32 - number of mask bits you need). So if you need lower 8 bits, you can right shift by (32-8 = 24) bits.

1 Comment

I thought that too, but since I convert my strings of hex to integers for other reasons they are negative, and it causes problems. Thanks though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.