java.math.BigInteger shiftLeft(int n)
Description
floor(this * 2n)
.)
Let’s take a for example a BigInteger 12
which is equivalent to binary 1100
. So if we have a value n=1
, then the binary 1100
shifted to the left by 1
would become 11000
. The equivalent of 11000
is 24
which be the returned value of the method shiftLeft()
.
Notes:
- this method is related to shiftRight().
Method Syntax
public BigInteger shiftLeft(int n)
Method Argument
Data Type | Parameter | Description |
---|---|---|
int | n | index of bit to shift. |
Method Returns
The flipBit() method this << n
Compatibility
Requires Java 1.1 and up
Java BigInteger shiftLeft(int n) Example
Below is a java code demonstrates the use of shiftLeft(int n) method of BigInteger class. The example presented might be simple however it shows the behavior of the shiftLeft(int n) method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Scanner; /* * A java example source code to demonstrate * the use of shiftLeft(int n) method of BigInteger class */ public class BigIntegerShiftLeftExample { public static void main(String[] args) { // initialize a BigInteger object BigInteger val1 = new BigInteger("17"); /* * Note: 17 in binary is 10001 */ // get user input System.out.print("Enter the shift distance:"); Scanner s = new Scanner(System.in); String input = s.nextLine(); s.close(); /* * convert the input to Integer unboxing feature will be used to * transform Integer to primitive int */ Integer inputBitNumber = Integer.parseInt(input); // get the new BigInteger BigInteger result = val1.shiftLeft(inputBitNumber); System.out.println("Result of the operation:" + result); } }
This example is a lot simpler than it looks. The first part is the declaration of a BigInteger. User are then asked to provide the shift distance. We then shifted the BigInteger object to the left with the specified shift distance. Result is printed at the end.