Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Complete Reference for Bitwise Operators in Programming/Coding
Next article icon

Complete Reference for Bitwise Operators in Programming/Coding

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

There exists no programming language that doesn't use Bit Manipulations. Bit manipulation is all about these bitwise operations. They improve the efficiency of programs by being primitive, fast actions. There are different bitwise operations used in bit manipulation. These Bitwise Operators operate on the individual bits of the bit patterns. Bit operations are fast and can be used in optimizing time complexity.

Table of Content

  • 1. Bitwise AND Operator (&)
  • 2. ​Bitwise OR Operator (|)
  • 3. ​Bitwise XOR Operator (^)
  • 4. ​Bitwise NOT Operator (!~)
  • 5. Left-Shift (<<)
  • 6. Right-Shift (>>)


Some common bit operators are:

Bitwise Operator Truth Table
Bitwise Operator Truth Table

1. Bitwise AND Operator (&)

The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. The & operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Truth table of AND operator
Truth table of AND operator

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise and of 7 & 4
Bitwise ANDof (7 & 4)

Implementation of AND operator:

C++
#include 
using namespace std;

int main()
{

    int a = 7, b = 4;
    int result = a & b;
    cout << result << endl;

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main (String[] args) {
        int a = 7, b = 4;
          int result = a & b;
          System.out.println(result);
    }
}

// This code is contributed by lokeshmvs21.
Python3
a = 7
b = 4
result = a & b
print(result)
# This code is contributed by akashish__
C#
using System;

public class GFG{

    static public void Main (){
      int a = 7, b = 4;
      int result = a & b;
      Console.WriteLine(result);
    }
}

// This code is contributed by akashish__
JavaScript
let a = 7, b = 4;
let result = a & b;
console.log(result);
// This code is contributed by akashish__

Output
4

Time Complexity: O(1) 
Auxiliary Space: O(1)

2. ​Bitwise OR Operator (|)

The | Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.

BItwiseORoperatortruthtable-300x216-(2)

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, y

Bitwise OR of (7 | 4)

Explanation: On the basis of truth table of bitwise OR operator we can conclude that the result of 

1 | 1  = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

We used the similar concept of bitwise operator that are show in the image.

Implementation of OR operator:

C++
#include 
using namespace std;

int main()
{

    int a = 12, b = 25;
    int result = a | b;
    cout << result;

    return 0;
}
Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int a = 12, b = 25;
        int result = a | b;
        System.out.println(result);
    }
}
Python3
a = 12
b = 25
result = a | b
print(result)

# This code is contributed by garg28harsh.
C#
using System;

public class GFG{

    static public void Main (){
        int a = 12, b = 25;
        int result = a | b;
        Console.WriteLine(result);
    }
}
// This code is contributed by akashish__
JavaScript
    let a = 12, b = 25;
    let result = a | b;
    document.write(result);
      
// This code is contributed by garg28harsh.

Output
29

Time Complexity: O(1) 
Auxiliary Space: O(1)

3. ​Bitwise XOR Operator (^)

The ^ operator (also known as the XOR operator) stands for Exclusive Or. Here, if bits in the compared position do not match their resulting bit is 1. i.e, The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite, otherwise 0.

BItwiseXORoperatortruthtable-300x216-(1)

Example: 

Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise OR of (7 ^ 4)

Explanation: On the basis of truth table of bitwise XOR operator we can conclude that the result of 

1 ^ 1  = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0

We used the similar concept of bitwise operator that are show in the image.

Implementation of XOR operator:

C++
#include 
using namespace std;

int main()
{

    int a = 12, b = 25;
    cout << (a ^ b);
    return 0;
}
Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int a = 12, b = 25;
        int result = a ^ b;
        System.out.println(result);
    }
}

// This code is contributed by garg28harsh.
Python3
a = 12
b = 25
result = a ^ b
print(result)

# This code is contributed by garg28harsh.
C#
// C# Code

using System;

public class GFG {

    static public void Main()
    {

        // Code
        int a = 12, b = 25;
        int result = a ^ b;
        Console.WriteLine(result);
    }
}

// This code is contributed by lokesh
JavaScript
let a = 12;
let b = 25;
console.log((a ^ b));
// This code is contributed by akashish__

Output
21

Time Complexity: O(1) 
Auxiliary Space: O(1)

4. ​Bitwise NOT Operator (!~)

All the above three bitwise operators are binary operators (i.e, requiring two operands in order to operate). Unlike other bitwise operators, this one requires only one operand to operate.

The bitwise Not Operator takes a single value and returns its one’s complement. The one’s complement of a binary number is obtained by toggling all bits in it, i.e, transforming the 0 bit to 1 and the 1 bit to 0.

Truth Table of Bitwise Operator NOT
Truth Table of Bitwise Operator NOT

Example: 

Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

Explanation: On the basis of truth table of bitwise NOT operator we can conclude that the result of 

~1  = 0
~0 = 1

We used the similar concept of bitwise operator that are show in the image.

Implementation of NOT operator:

C++
#include 
using namespace std;

int main()
{

    int a = 0;
    cout << "Value of a without using NOT operator: " << a;
    cout << "\nInverting using NOT operator (with sign bit): " << (~a);
    cout << "\nInverting using NOT operator (without sign bit): " << (!a);

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
  public static void main(String[] args)
  {
    int a = 0;
    System.out.println(
      "Value of a without using NOT operator: " + a);
    System.out.println(
      "Inverting using NOT operator (with sign bit): "
      + (~a));
    if (a != 1)
      System.out.println(
      "Inverting using NOT operator (without sign bit): 1");
    else
      System.out.println(
      "Inverting using NOT operator (without sign bit): 0");
  }
}

// This code is contributed by lokesh.
Python3
a = 0
print("Value of a without using NOT operator: " , a)
print("Inverting using NOT operator (with sign bit): " , (~a))
print("Inverting using NOT operator (without sign bit): " , int(not(a)))
#  This code is contributed by akashish__
C#
using System;

public class GFG {

  static public void Main()
  {

    int a = 0;
    Console.WriteLine(
      "Value of a without using NOT operator: " + a);
    Console.WriteLine(
      "Inverting using NOT operator (with sign bit): "
      + (~a));
    if (a != 1)
      Console.WriteLine(
      "Inverting using NOT operator (without sign bit): 1");
    else
      Console.WriteLine(
      "Inverting using NOT operator (without sign bit): 0");
  }
}

// This code is contributed by akashish__
JavaScript
    let a =0;
    document.write("Value of a without using NOT operator: " + a);
    document.write( "Inverting using NOT operator (with sign bit): " + (~a));
    if(!a)
    document.write( "Inverting using NOT operator (without sign bit): 1" );
    else
    document.write( "Inverting using NOT operator (without sign bit): 0" );

    

Output
Value of a without using NOT operator: 0
Inverting using NOT operator (with sign bit): -1
Inverting using NOT operator (without sign bit): 1

Time Complexity: O(1) 
Auxiliary Space: O(1)

5. Left-Shift (<<)

The left shift operator is denoted by the double left arrow key (<<). The general syntax for left shift is shift-expression << k. The left-shift operator causes the bits in shift expression to be shifted to the left by the number of positions specified by k. The bit positions that the shift operation has vacated are zero-filled. 

Note: Every time we shift a number towards the left by 1 bit it multiply that number by 2.

Logical left Shift
Logical left Shift

Example:

Input: Left shift of 5 by 1.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)
 

Left shift of 5 by 1

Output: 10
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10

Input: Left shift of 5 by 2.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)

Left shift of 5 by 2

Output: 20
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20

Input: Left shift of 5 by 3.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)

Left shift of 5 by 3

Output: 40
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40

Implementation of Left shift operator:

C++
#include 
using namespace std;

int main()
{
    unsigned int num1 = 1024;

    bitset<32> bt1(num1);
    cout << bt1 << endl;

    unsigned int num2 = num1 << 1;
    bitset<32> bt2(num2);
    cout << bt2 << endl;

    unsigned int num3 = num1 << 2;
    bitset<16> bitset13{ num3 };
    cout << bitset13 << endl;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
  public static void main(String[] args)
  {
    int num1 = 1024;

    String bt1 = Integer.toBinaryString(num1);
    bt1 = String.format("%32s", bt1).replace(' ', '0');
    System.out.println(bt1);

    int num2 = num1 << 1;
    String bt2 = Integer.toBinaryString(num2);
    bt2 = String.format("%32s", bt2).replace(' ', '0');
    System.out.println(bt2);

    int num3 = num1 << 2;
    String bitset13 = Integer.toBinaryString(num3);
    bitset13 = String.format("%16s", bitset13)
      .replace(' ', '0');
    System.out.println(bitset13);
  }
}

// This code is contributed by akashish__
Python3
# Python code for the above approach

num1 = 1024

bt1 = bin(num1)[2:].zfill(32)
print(bt1)

num2 = num1 << 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)

num3 = num1 << 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)

# This code is contributed by Prince Kumar
C#
using System;

class GFG {
  public static void Main(string[] args)
  {
    int num1 = 1024;

    string bt1 = Convert.ToString(num1, 2);
    bt1 = bt1.PadLeft(32, '0');
    Console.WriteLine(bt1);

    int num2 = num1 << 1;
    string bt2 = Convert.ToString(num2, 2);
    bt2 = bt2.PadLeft(32, '0');
    Console.WriteLine(bt2);

    int num3 = num1 << 2;
    string bitset13 = Convert.ToString(num3, 2);
    bitset13 = bitset13.PadLeft(16, '0');
    Console.WriteLine(bitset13);
  }
}

// This code is contributed by akashish__
JavaScript
// JavaScript code for the above approach

let num1 = 1024;

let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);

let num2 = num1 << 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);

let num3 = num1 << 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);

Output
00000000000000000000010000000000
00000000000000000000100000000000
0001000000000000

Time Complexity: O(1) 
Auxiliary Space: O(1)

6. Right-Shift (>>)

The right shift operator is denoted by the double right arrow key (>>). The general syntax for the right shift is "shift-expression >> k". The right-shift operator causes the bits in shift expression to be shifted to the right by the number of positions specified by k. For unsigned numbers, the bit positions that the shift operation has vacated are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.

Note: Every time we shift a number towards the right by 1 bit it divides that number by 2.

Logical Right Shift
Logical Right Shift

Example:

Input: Left shift of 5 by 1.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)

Right shift of 5 by 1

Output: 10
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10

Input: Left shift of 5 by 2.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)

Right shift of 5 by 2

Output: 20
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20

Input: Left shift of 5 by 3.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)

Right shift of 5 by 3

Output: 40
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40

Implementation of Right shift operator:

C++
#include 
#include 

using namespace std;

int main()
{
    unsigned int num1 = 1024;

    bitset<32> bt1(num1);
    cout << bt1 << endl;

    unsigned int num2 = num1 >> 1;
    bitset<32> bt2(num2);
    cout << bt2 << endl;

    unsigned int num3 = num1 >> 2;
    bitset<16> bitset13{ num3 };
    cout << bitset13 << endl;
}
Java
// Java code for the above approach

class GFG {
    public static void main(String[] args)
    {
        int num1 = 1024;

        String bt1
            = String
                  .format("%32s",
                          Integer.toBinaryString(num1))
                  .replace(' ', '0');
        System.out.println(bt1);

        int num2 = num1 >> 1;
        String bt2
            = String
                  .format("%32s",
                          Integer.toBinaryString(num2))
                  .replace(' ', '0');
        System.out.println(bt2);

        int num3 = num1 >> 2;
        String bitset13
            = String
                  .format("%16s",
                          Integer.toBinaryString(num3))
                  .replace(' ', '0');
        System.out.println(bitset13);
    }
}

// This code is contributed by ragul21
Python
num1 = 1024
bt1 = bin(num1)[2:].zfill(32)
print(bt1)

num2 = num1 >> 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)

num3 = num1 >> 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)
C#
using System;

class Program
{
    static void Main()
    {
        int num1 = 1024;
        
        // Right shift by 1
        int num2 = num1 >> 1;
        
        // Right shift by 2
        int num3 = num1 >> 2;

        // Print binary representations
        string bt1 = Convert.ToString(num1, 2).PadLeft(32, '0');
        string bt2 = Convert.ToString(num2, 2).PadLeft(32, '0');
        string bitset13 = Convert.ToString(num3, 2).PadLeft(16, '0');

        Console.WriteLine(bt1);
        Console.WriteLine(bt2);
        Console.WriteLine(bitset13);
    }
}
JavaScript
// JavaScript code for the above approach

let num1 = 1024;

let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);

let num2 = num1 >> 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);

let num3 = num1 >> 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);
// akashish__

Output
00000000000000000000010000000000
00000000000000000000001000000000
0000000100000000

Time Complexity: O(1) 
Auxiliary Space: O(1)

Application of BIT Operators

  • Bit operations are used for the optimization of embedded systems.
  • The Exclusive-or operator can be used to confirm the integrity of a file, making sure it has not been corrupted, especially after it has been in transit.
  • Bitwise operations are used in Data encryption and compression.
  • Bits are used in the area of networking, framing the packets of numerous bits which are sent to another system generally through any type of serial interface.
  • Digital Image Processors use bitwise operations to enhance image pixels and to extract different sections of a microscopic image.

Next Article
Complete Reference for Bitwise Operators in Programming/Coding
author
kartik
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Programming
  • Bitwise-XOR
  • Bitwise-OR
  • Bitwise-AND
  • Bitwise Operators
Practice Tags :
  • Bit Magic

Similar Reads

    Bitwise Left Shift(<<) Operator in Programming
    Bitwise operators play a significant role in manipulating individual bits within binary data. Among these operators, the Bitwise Left Shift (<<) operator is used for shifting the bits of a number to the left by a specified number of positions. In this blog post, we'll explore the definition, s
    5 min read
    Bitwise XOR Operator in Programming
    Bitwise XOR Operator is represented by the caret symbol (^). It is used to perform a bitwise XOR operation on the individual bits of two operands. The XOR operator returns 1 if the corresponding bits in the two operands are different, and 0 if they are the same.Table of Content What is Bitwise XOR?B
    5 min read
    Bitwise OR Operator (|) in Programming
    In programming, Bitwise Operators play a crucial role in manipulating individual bits of data. One of the fundamental bitwise operators is the Bitwise OR operator (|). In this article, we’ll discuss the Bitwise OR operator, its syntax, properties, applications, and optimization techniques, and concl
    5 min read
    Bitwise Hacks for Competitive Programming
    Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).   First, we left shift '1' to n position via (1<
    14 min read
    Bitwise AND operator in Programming
    In programming, Bitwise Operators play a crucial role in manipulating individual bits of data. One of the fundamental bitwise operators is the Bitwise AND operator (&). In this article, we'll dive deep into what is Bitwise AND operator, its syntax, properties, applications, and optimization tech
    6 min read
    Program for Bitwise Operators in C, C++, Java, Python, C# & JavaScript
    Bitwise operators are fundamental operators used in computer programming for manipulating individual data bits. They operate at the binary level, performing operations on binary data representations. These operators are commonly used in low-level programming, such as device drivers, embedded systems
    9 min read
    Binary Operators in Programming
    Binary Operators are essential tools in programming that perform operations on pairs of data, enabling tasks like calculations, comparisons, logical operations, and bitwise manipulations. They are fundamental for processing and manipulating data efficiently in computer programs. Table of Content Wha
    14 min read
    Types of Operators in Programming
    Types of operators in programming are symbols or keywords that represent computations or actions performed on operands. Operands can be variables, constants, or values, and the combination of operators and operands form expressions. Operators play a crucial role in performing various tasks, such as
    15+ min read
    Logical Operators in Programming
    Logical Operators are essential components of programming languages that allow developers to perform logical operations on boolean values. These operators enable developers to make decisions, control program flow, and evaluate conditions based on the truthiness or falsiness of expressions. In this a
    3 min read
    Logical NOT Operator in Programming
    In programming, Logical operators play a crucial role in manipulating data. One of the fundamental logical operators is the Logical NOT operator(!).In this article, we’ll discuss the Logical NOT operator, its syntax, properties, applications, and optimization techniques, and conclude with its signif
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences