Bitwise Algorithms - GeeksforGeeks (2024)

Last Updated : 03 Apr, 2024

Improve

Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, shift operators, etc., to solve problems related to tasks such as setting, clearing, or toggling specific bits, checking if a number is even or odd, swapping values without using a temporary variable, and more. Bitwise algorithms are crucial in optimizing code for speed and memory usage in various programming scenarios.

Table of Content

  • What are Bitwise Algorithms?
  • Common Bitwise Algorithms and Operations
  • Applications of Bitwise Algorithms
  • Basics of Bitwise Algorithms
  • Bit Manipulation Tips and Tricks
  • Easy Problems on Bit Algorithms
  • Medium Problems on Bit Algorithms
  • Hard Problems on Bit Algorithms

What are Bitwise Algorithms?

Bitwise algorithms are algorithms that operate on individual bits of data rather than on larger data types like integers or floating-point numbers. These algorithms manipulate bits directly, typically using bitwise operators such as AND, OR, XOR, shift left, shift right, and complement.

Common Bitwise Algorithms and Operations:

Here are some common bitwise algorithms and operations:

  • Bitwise AND (&): Takes two numbers as input and performs a bitwise AND operation on their corresponding bits. It returns 1 only if both bits are 1; otherwise, it returns 0.
  • Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two numbers. It returns 1 if at least one of the bits is 1.
  • Bitwise XOR (^): Performs a bitwise exclusive OR operation on the corresponding bits of two numbers. It returns 1 if the bits are different and 0 if they are the same.
  • Bitwise NOT (~): Performs a bitwise NOT operation, which flips each bit of the input (1 becomes 0 and 0 becomes 1).
  • Left Shift (<<) and Right Shift (>>): These operators shift the bits of a number to the left or right by a specified number of positions. Left shifting is equivalent to multiplying the number by 2, while right shifting is equivalent to dividing by 2.

Applications of Bitwise Algorithms:

  • Bit manipulation (setting, clearing, toggling bits): Bitwise operators are often used to manipulate individual bits of numbers. This includes tasks such as setting bits (using OR), clearing bits (using AND with the complement), toggling bits (using XOR with 1), and checking the value of a specific bit.
  • Efficient storage of data: Bitwise algorithms play a crucial role in data compression techniques like Huffman coding. They can efficiently represent and process compressed data by manipulating bits directly.
  • Cryptography: Many cryptographic algorithms, such as AES (Advanced Encryption Standard), DES (Data Encryption Standard), and SHA (Secure Hash Algorithm), utilize bitwise operations for encryption, decryption, and hashing. Bitwise XOR, in particular, is commonly used in encryption algorithms for its simplicity and effectiveness.
  • Networking and Protocol Handling: Bitwise algorithms are used in networking protocols for tasks like IP address manipulation, subnet masking, and packet parsing. For example, bitwise AND is used in subnet masking to determine the network address from an IP address and subnet mask.
  • Low-Level System Programming: Bitwise operations are essential in low-level system programming for tasks such as device control, memory management, and bit-level I/O operations. They are used to manipulate hardware registers, set/clear flags, and optimize code for performance.
  • Error Detection and Correction: Bitwise algorithms are employed in error detection and correction techniques, such as CRC (Cyclic Redundancy Check) and Hamming codes. These algorithms use bitwise XOR and other operations to detect and correct errors in transmitted data.

Basics of Bitwise Algorithms:

  • Introduction to Bitwise Algorithms – Data Structures and Algorithms Tutorial
  • Complete Reference for Bitwise Operators in Programming/Coding
  • Bitwise Operators in C/C++
  • Bitwise Operators in Java
  • Python Bitwise Operators
  • JavaScript Bitwise Operators
  • All about Bit Manipulation
  • Little and Big Endian Mystery

Bit Manipulation Tips and Tricks

  • Bits manipulation (Important tactics)
  • Bitwise Hacks for Competitive Programming

Easy Problems on Bit Algorithms:

  • Binary representation of a given number
  • Count set bits in an integer
  • Add two bit strings
  • Turn off the rightmost set bit
  • Rotate bits of a number
  • Compute modulus division by a power-of-2-number
  • Find the Number Occurring Odd Number of Times
  • Program to find whether a no is power of two
  • Find position of the only set bit
  • Check for Integer Overflow
  • Find XOR of two number without using XOR operator
  • Check if two numbers are equal without using arithmetic and comparison operators
  • Detect if two integers have opposite signs
  • How to swap two numbers without using a temporary variable?
  • Russian Peasant (Multiply two numbers using bitwise operators)

Medium Problems on Bit Algorithms:

  • Swap bits in a given number
  • Smallest of three integers without comparison operators
  • Compute the minimum or maximum of two integers without branching
  • Smallest power of 2 greater than or equal to n
  • Program to find parity
  • Check if binary representation of a number is palindrome
  • Generate n-bit Gray Codes
  • Check if a given number is sparse or not
  • Euclid’s Algorithm when % and / operations are costly
  • Calculate square of a number without using *, / and pow()
  • Cyclic Redundancy Check and Modulo-2 Division
  • Copy set bits in a range
  • Check if a number is Bleak
  • Gray to Binary and Binary to Gray conversion

Hard Problems on Bit Algorithms:

  • Next higher number with same number of set bits
  • Karatsuba algorithm for fast multiplication
  • Find the maximum subarray XOR in a given array
  • Find longest sequence of 1’s in binary representation with one flip
  • Closest (or Next) smaller and greater numbers with same number of set bits
  • Bitmasking and Dynamic Programming | Set-2 (TSP)
  • Compute the parity of a number using XOR and table look-up
  • XOR Encryption by Shifting Plaintext
  • Count pairs in an array which have at least one digit common
  • Python program to convert floating to binary
  • Booth’s Multiplication Algorithm
  • Number of pairs with Pandigital Concatenation
  • Find the n-th number whose binary representation is a palindrome
  • Find the two non-repeating elements in an array of repeating elements

Quick Links :

  • Learn Data Structure and Algorithms | DSA Tutorial
  • ‘Practice Problems’ on Bit Magic
  • ‘Quiz’ on Bit Magic
  • ‘Videos’ on Bit Magic


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Bitwise Algorithms - GeeksforGeeks (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Neely Ledner

Last Updated:

Views: 6589

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.