topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Bitwise Operators in Java - Scaler Topics description: This article by Scaler Topics will discuss about the case of a sentence and see if the number is even or odd with the help of Bitwise operators. author: Atul Sharma category: Java --- :::section{.abstract} `Bitwise` operators in Java are among those operators that perform their tasks at a `binary level` directly on `binary digits` (also known as bits), the smallest form of data in a computer or its data types. These `bitwise operators` are faster and an efficient way to interact with computers to make heavy computation in a `linear time` because they work directly with the bits rather than through a `level of abstraction` of software. The image below shows the steps required to perform arithmetic operations on decimal and binary data. ![steps in arithmetic operation](https://scaler.com/topics/images/steps-in-arithmetic-operation.webp) `Bit Manipulation` is performed using Bitwise Operators in Java on each bit of a number individually and can be used with any data type, such as int, float, short, char, etc. Bitwise operators work internally on a **binary equivalent of decimal numbers**, i.e. the operation is performed on decimal numbers and internally, these operators work on individual bits `bit by bit`, as per the given operations: The process begins by converting the operands into binary form. Then, the operator is executed on each binary number, producing the result. Finally, the resulting binary value is converted back into its decimal representation. Standard arithmetic operators perform operations on human-readable values `(3+4)`, while bitwise operators manipulate the low-level data directly. ::: :::section{.main} ## Types of Bitwise Operators in Java There are six types of bitwise operator in Java: 1. Bitwise AND 2. Bitwise inclusive OR 3. Bit Shift Operators 4. Bitwise Compliment 5. Bitwise exclusive OR ![Types of Java Bitwise Operators in Java](https://scaler.com/topics/images/types-of-java-bitwise-operators-in-java.webp) | Operators | Symbol | Uses | | :---: | :---: | :---: | | Bitwise AND | ``&`` | num1 & num2 | | Bitwise Exclusive OR (XOR) | ``^`` | num1 ^ num2 | | Bitwise Inclusive OR | \\| | num1 \\| num2 | | Bitwise Complement | ``~`` | ~ num | | Bitwise Left shift | ``<<`` | num1 << num2 | | Bitwise Right shift | ``>>`` | num1 >> num2 | | Unsigned Right Shift Operator | ``>>>`` | num1>>>num2 | Let's go through all these operators one by one. ::: :::section{.main} ## Bitwise AND(``&``) `AND (&)` is a important binary operator which compares two binary operands of equal `bit` length. For every `bit`, the operation checks if both bits are `1` across both `operands`. If `true`, `bit` will be set to `1` in the answer. Else, the resulting bit is set to `0`. Its Truth Table: ```java 1 & 0 => gives 0 0 & 1 => gives 0 0 & 0 => gives 0 1 & 1 => gives 1 ``` **Example:** We want to perform Bitwise AND Operation of 6 and 8 (6 & 8), then. a = 6 = 0110 (In Binary) b = 8 = 1000 (In Binary) 0110 & 1000 ________ 0000 = 0 (In decimal) ::: :::section{.main} ## Bitwise OR(``|``) The OR operaor is denoted by '|'. It perform bitwise (i.e bit by bit) or of input operands, if either of bits is 1 then it will give 1 otherwise it will give 0. **Its Truth Table:** ```java 1 | 0 => gives to 1 0 | 1 => gives to 1 1 | 1 => gives to 1 0 | 0 => gives to 0 ``` **Example:** We want to perform Bitwise OR Operation of 6 and 8 (`6 | 8`), then a = 6 = 0110 (In Binary) b = 8 = 1000 (In Binary) 0110 | 1000 ________ 1110 = 14 (In decimal) ::: :::section{.main} ## Bitwise Complement (`~`) The Bitwise Not means the `negation` of each `bit` of the input value. It takes only one `integer`. It is also called Complement operator. All samples of `0` become `1`, and all samples of `1` become `0`. In other words, `NOT` invert each input bit. This inverted cycle is called the 1’s complement of a bit series. This makes the number negative as any `bit` sequence starting with `1` is negative, as here `N = ~N` always produce results `-(N+1)`. Because the system store data in the form of 2's complement which means it stores `~N` like this. ```java ~N = -(~(~N)+1) =-(N+1). ``` **Example:** We want to perform a Bitwise Complement of `6 (~6)`, then 1. Representing the number in binary format `a = 6 => 0110` (In Binary) 2. Now we have to find `~6`(means `1's` compliment of `6`) `0000 0110 => 1111 1001` (flip each `1's` to `0` and vice versa) So, ``~6 = 1111 1001``, Here, MSB(Most Significant Bit) is 1(means negative value). Then, in memory, it will be represented as 2's compliment (To find 2's compliment, we first have to find 1's compliment and then add 1 to it.) 3. Finding `2's` compliment of ~6 i.e 1111 1001 ```java 1's compliment Adding 1 to it 1111 1001 ==================> 0000 0110 =================> 0000 0110 + 1 --------- 0000 0111 So, 2's compliment of 1111 1001, is 0000 0111 ``` 4. Converting back to decimal format. 0000 0111 => 7 In step2: we have seen that the number is negative, so the final answer would be -7 So, ~6 === -7 (result of bitwise complement) ::: :::section{.main} ## Bitwise XOR (``^``) The `bitwise XOR operation (^)` is a binary operator that takes two input states and compares each corresponding bit. If the bits are opposite, the solution has a `1` in that `bit` position, and if they are matched, a `0` is returned. ```java 1 ^ 1 => gives 0. 0 ^ 0 => gives 0. 1 ^ 0 => gives 1. 0 ^ 1 => gives 1. ``` **Example:** We want to perform Bitwise XOR Operation of 6 and 8 (6 ^ 8), then. a = 6 = 0110 (In Binary) b = 8 = 1000 (In Binary) 0110 ^ 1000 ________ 1110 = 14 (In decimal) ::: :::section{.tip} * `XOR` is used to flip selected single bits in a `register` or replace bit patterns that show `Boolean` states. * It is widely used in cryptography and in producing `parity bits` to check error and fault tolerance. ::: :::section{.main} ## Bit Shift (`>>, <<,>>>`) A "bit shift" refers to a fundamental bitwise operation used to manipulate binary data efficiently in computing. It involves moving the positions of binary digits within a number's representation either to the left or right, based on a specified number of spaces indicated by the second operand. This operation can be applied to integral data types including integers (such as int, long, short), bytes, and characters (char). There are four types of shifts: 1. Signed Left shift operator (<<) 2. Signed Right shift operator(>>) 3. Unsigned Left shift operator (<<<) 4. Unsigned Right shift operator (>>>) **a. `Signed Left shift operator`**: `<<` is the left shift operator and meets both logical and arithmetic shifts’ needs. ![left shift operator](https://www.scaler.com/topics/images/left-shift-operator-cor.webp) **Example:** ```java // left shift of 2 2 = 0010 (In Binary) // perform 2 bit left shift 2 << 2: 0010 << 2 = 1000 (equivalent to 8) ``` **b. `Arithmetic/signed right shift`**: `>>` is the arithmetic (or signed) right shift operator. **Example:** ```java // right shift of 8 8 = 1000 (In Binary) // perform 2 bit right shift 8 >> 2: 1000 >> 2 = 0010 (equivalent to 2) ``` **c. `Unsigned Left shift operator`**: `<<<` is the logical (or unsigned) left shift operator. It performs the same operation as the left shift operator, but its sign is not preserved. **d. `Unsigned Right shift operator`**: `>>>` is the logical (or unsigned) right shift operator. It performs the same operation as the right shift operator, but its sign is not preserved in the operation. ![right shift operator](https://scaler.com/topics/images/right-shift-operator.webp) **Example:** ```java // unsigned right shift of 8 8 = 0000 1000 (In Binary) // Unsigned shift ``>>>`` will not keep the sign bit // (thus filling 0s) for positive numbers 8 >>> 2 = 0000 0010 ==> 2 (in decimal) // unsigned right shift of ``-8`` // however, here numbers are not filled with zero as above -8 = 1111 1000 (see calculation above) -8 >>> 2 = 1111 1110 ==> 254 (in decimal) ``` ::: :::section{.main} ## Advantages of Bitwise Operators in Java 1. You will have situations where you would like to `set/clear/toggle` just one specific bit of a register without operating on the whole register. Using bitwise operators in Java, you can do a read and perform an `OR/AND/XOR` operation with the suitable mask to modify only the desired bit position. 2. Usually, bitwise operations are faster than doing multiply/divide. 3. Similarly, if you wish to use an array as a circular queue, it'd be faster(and more elegant) to handle wraparound checks with bit-wise operations (your array size should be a power of 2). 4. Also, if you want a program `error flag' to hold multiple error codes together for multiple scenarios, each bit can hold a separate value. You can `AND` it with each error code as a check. One such use case is `Unix error codes`. 5. Also, a `n-bit bitmap` can be a compact data structure. If you want to allocate a resource pool of size n, we can use n-bits to represent the current status. 6. In `Compression & Encryption`, both heavily depend on bitwise algorithms. For example, look at the deflate algorithm - everything is in bits, not bytes. For example:- `Huffman Coding` (for compression) and `Data Encryption` Standard (for encryption) ::: :::section{.summary} ## Conclusion - Bitwise operators in Java are faster than standard arithmetic operators, which operate on decimal numbers. Logical and Bitwise operations are two different types of operations. The former operate on boolean data types, whereas the latter operate on bits. - **AND** bitwise operator returns 1 if both bits are set. - **OR** bitwise operator returns 1 if at least one of the operand bits is set. - **XOR** bitwise operator returns 1 if the operand bits are opposite in value. ::: :::section{.faqs} ## FAQs **Q1. What are bitwise operators?** **A:** Bitwise operators in java are operators used to manipulate individual bits of binary numbers. **Q2. How many bitwise operators are there?** **A:** There are six bitwise operators in most programming languages: AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). **Q3. In which scenarios are bitwise operators commonly used?** **A:** Bitwise operators are commonly used in low-level programming, such as device drivers, embedded systems, cryptography, and optimization tasks. **Q4. Are bitwise operators platform-independent?** **A:** Yes, Bitwise operators themselves are generally platform-independent. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully