Home > Enterprise >  Why use bitwise operation (<<) to double int value
Why use bitwise operation (<<) to double int value

Time:03-21

Wondering why does Java use << 1 extensively to double an Integer's value?
e.g. in HashMap there's

// HashMap#resize
newThr = oldThr << 1; // double threshold

I believe the performance between << 1 and * 2 is similar?

CodePudding user response:

Although you can argue that performace between the binary shift vs arithmentic multiplication using operator are almost same in modern CPUs , bitwise operations are absolutely essential when programming hardware registers in embedded systems.Generally bitwise operations come into play a lot when you need to encode/decode data in a compact and fast way.These kind of operations are often used when writing for embedded systems where memory or CPU power is restricted.For example, to save space you may store multiple variables in a single 8-bit int variable by using each bit to represent a boolean. Then you need a fast way to set a specific bit or retrieve the bit value.The storage capacity of many embedded systems is 64, 128 or 256 BYTES (that is bytes, not kilobytes or megabytes). In this environment, it is common to use one byte to store multiple data items, boolean flags etc., and then use bit operations to set and read them.

The bit-wise operators are also common in video and audio codecs for the same reason embedded electronics use them; if you want a super-efficient video codec, having five flags and an eleven-bit timer in half an int is great. Bit-wise operators are more about readability these days.

  • Related