A strange way to assign a variable

I worked in C ++ and Java, and in both languages, which I often came across in a weird way of assigning variables using bitwise operators. Instead of what could be a simple assignment using an assignment operator, it is more complicated using bitwise operators such as left shift. For example, in the Java ServerSocketChannel class, we see the following assignments:

public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;

I am trying to understand here what we got using the <operator. We could make simple assignments for assigning variables as 1,4,8,16 respectively, as shown below:

public static final int OP_READ = 1;
public static final int OP_WRITE = 4; 
public static final int OP_CONNECT = 8; 
public static final int OP_ACCEPT = 16;  

What adds value when using the operator <<here?

+4
source share
2 answers

/ ( ).

OP_ACCEPT = 16 OP_ACCEPT = 1 << 4 - ( javap -constants <YourClass>)

, . , , .

HashMap ( HashXXX ), , , java, , . , :

 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

, , , , :

static final int TREEIFY_THRESHOLD = 8;
static final int MIN_TREEIFY_CAPACITY = 64

, , , HashMap (n - 1) & hash, n - ( - ). 16 ( 1 << 4) , 4 , 1 . , 1 << 4 HashMap , 4 ( ). 1 << 28 ... , .

, , , or and, .

+3

, "" "". ACL - ; 4 (, , , ), 1 , 4.

shift 1 , 2.

, 5 = 0101 , 1 1010, 10.

-4

Source: https://habr.com/ru/post/1694469/


All Articles