How to create 32 bit mask in Java

19,041

Here's how to create a 32 bit mask in Java.

int mask = 0x00010000;  // for example.

And if you want to create a 32 bit mask with bit N set then

int mask = 1 << N;  // Assumes the rightmost bit is numbered zero ...

And if you want to create an array of masks, then just do the above in a loop, in the obvious fashion.

int[] masks = new int[32];
for (int n = 0; n < 32; n++) {
    masks[n] = 1 << n;
}

In reality, your supposed "16 bit masks" are also 32 bit masks, because int is a 32 bit type in Java.

And like @Matt Ball, I'm puzzled as to what you are really trying to do, and whether you are going about it is a sensible way to achieve it. Why do you need an array of masks when you can create a mask on the fly with less code?

Share:
19,041
uohzxela
Author by

uohzxela

Updated on June 04, 2022

Comments

  • uohzxela
    uohzxela almost 2 years

    So far I have this code to create 16 bit mask. However I do not know how to create a 32 bit mask using this approach. Any ideas?

    edit: I want to create 32 masks of 32 bits, each with with its respective bit being 1 and the rest of the bits being zero. For example: mask 1 has the leftmost bit being 1 while the rest of the bits are zero, mask 2 has the 2nd leftmost bit being 1 while the rest of the bits are zero. I dunno how to explain more succinctly but I hope you guys get the idea...

    mask = new int[16];
    mask[0] = 0x8000;
    mask[1] = 0x4000;
    mask[2] = 0x2000;
    mask[3] = 0x1000;
    
    mask[4] = 0x0800;
    mask[5] = 0x0400;
    mask[6] = 0x0200;
    mask[7] = 0x0100;
    
    mask[8] = 0x0080;
    mask[9] = 0x0040;
    mask[10] = 0x0020;
    mask[11] = 0x0010;
    
    mask[12] = 0x0008;
    mask[13] = 0x0004;
    mask[14] = 0x0002;
    mask[15] = 0x0001
    
  • uohzxela
    uohzxela over 10 years
    Sorry for the unclear question. I edited it. Hope it makes sense now.
  • Dolda2000
    Dolda2000 over 10 years
    "Assumes the leftmost bit is numbered zero ..." -- It actually assumes the rightmost bit is numbered zero. ;)
  • uohzxela
    uohzxela over 10 years
    Many thanks. Your answer clears some air and steered me in the right direction.
  • Aaron Dancygier
    Aaron Dancygier about 10 years
    This won't work Math.pow(x,y) returns double. You will have to cast to long. mask[i] = (long) Math.pow(2,i);