home     blog     about     contact
Daniel Strecker's Blog - daniel-strecker.com
published: 2020-05-24
started: 2020-05-24
last change: 2020-05-24

Bitmask Tricks



// int
// starting to count from highest bit, n = 5
int a =   -1 >>> n ; // 00000111111111111111111111111111₂ (all but highest n bits set)
int b = ~(-1 >>> n); // 11111000000000000000000000000000₂ (highest n bits set)

// starting to count from lowest bit, n = 5
int c =   -1  << n ; // 11111111111111111111111111100000₂ (all bits higher than n set)
int d = ~(-1  << n); // 00000000000000000000000000011111₂ (lowest n bits set)

// long
// starting to count from highest bit, n = 5
long e =   -1L >>> n ; // 0000011111111111111111111111111111111111111111111111111111111111₂ (all but highest n bits set)
long f = ~(-1L >>> n); // 1111100000000000000000000000000000000000000000000000000000000000₂ (highest n bits set)

// starting to count from lowest bit, n = 5
long g =   -1L  << n ; // 1111111111111111111111111111111111111111111111111111111111100000₂ (all bits higher than n set)
long h = ~(-1L  << n); // 0000000000000000000000000000000000000000000000000000000000011111₂ (lowest n bits set)

Snippet 1: BitmaskTricks in Java

You can find ready to run code in BitmaskTricks.java.