Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to use shift operators in java?

Tags:

  1. What is the purpose of using Shift operators rather than using division and multiplication?

  2. Are there any other benefits of using shift operators?

  3. Where should one try to use the shift operator?

like image 527
Saravanan Avatar asked Sep 17 '11 12:09

Saravanan


People also ask

Why do we use Shift?

The Shift key ⇧ Shift is a modifier key on a keyboard, used to type capital letters and other alternate "upper" characters. There are typically two shift keys, on the left and right sides of the row below the home row.

What is the use of << shift operator?

The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

Why do we need to bit shift?

A bit shift is a bitwise operation where the order of several bits is moved, either to the left or right, to efficiently perform a mathematical operation. Bit shifts help with optimization in low-level programming because they require fewer calculations for the CPU than conventional math.

What is the need to have two right shift operators in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.


1 Answers

Division and multiplication are not really a use of bit-shift operators. They're an outdated 'optimization' some like to apply.

They are bit operations, and completely necessary when working at the level of bits within an integer value.

For example, say I have two bytes that are the high-order and low-order bytes of a two-byte (16-bit) unsigned value. Say you need to construct that value. In Java, that's:

int high = ...; int low = ...; int twoByteValue = (high << 8) | low; 

You couldn't otherwise do this without a shift operator.

To answer your questions: you use them where you need to use them! and nowhere else.

like image 155
Sean Owen Avatar answered Sep 18 '22 22:09

Sean Owen