The Bitwise Operators

By: aathishankaran Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The Bitwise Operators

 

            Java defines several Bitwise operations, which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following table:

 

            Operator                     Result

           

            ~                                  Bitwise unary NOT

            &                                 Bitwise AND

            !                                   Bitwise OR

            ^                                  Bitwise exclusive OR

            >>                                Shift right

            >>>                             Shift right zero fill

            <<                                Shift left

            &=                               Bitwise AND assignment

            !=                                 Bitwise OR assignment

            ^=                                Bitwise exclusive OR assignment

            >>=                             Shift right assignment

            >>>=                           Shift right zero fill assignment

            <<=                             Shift left assignment

 

            Since the Bitwise operators manipulate the bits within an integer, it is important to understand what effects such manipulations may have on a value. Specifically, it is useful to know how java stores integer values and how it represents negative numbers. So, before continuing, let’s briefly review these two topics.

 

            The entire integer types are represented by binary numbers of varying bit widths.

 

            All of the integer types (expect char) are signed integers. This means that they can represent negative values as well as positive ones. Java uses an encoding known as two’s complement, which means that negative numbers are represented by inverting (changing 1’s to 0’s and vice versa) all of the bits in a value, then adding 1 to the result. For example, -42 us represented by inverting all of the bits in 42, or 00101010, which yields 11010101, then adding 1, which results in 11010110, or –42. to decode a negative number, first invert all of the bits, then add 1. –42, or 11010110 inverted yields 00101001, or 41, so when you add 1 you get 42.

 

            The reason java (and most other computer languages) uses two’s complement is easy to see when you consider the issue of zero crossing. Assuming a byte value, zero is represented by 00000000. in one’s complement, simply inverting all of the bits creates 11111111, which creates negative zero. The trouble is that negative zero is invalid in integer math. Using two’s complement to represent negative values solves this problem. When using two’s complement, 1 is added to the complement, producing 10000000. this produces a 1 bit too far to the left to fit back into the byte value, resulting in the desired behavior, where –0 is the same as 0, and 11111111 is the encoding for  -1. although we used a byte value in the preceding example, the same basic principle applies to all of java’s integer types.

 

            Because java uses two’s complement to store negative numbers and because all integers are signed values in java applying the Bitwise operators can easily produce unexpected results. For example, turning on the high-order bit will cause the resulting value to be interpreted as a negative number, whether this is what you intended or not. To avoid unpleasant surprises, just remember that the high-order bit determines the sign of an integer no matter how that high-order bit gets set.

 

Note: This is an extract from the book "Java: The Complete Reference" by Herbert Schildts

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

hello, that was very useful
but i have a byte array that i need to left/right shift.the reason for that is i have to encode a string containing 8-bit-character to 7-bit-character (and then decode it). how can i do the shifting or even Better, the encoding ?

thank you very much ;)

i am using J2ME by the way


View Tutorial          By: echo at 2011-04-05 11:50:41
2. View Comment

Bitwise OR is a pipe (|), not a logical NOT (!)

View Tutorial          By: Martijn at 2011-06-21 10:49:29
3. View Comment

please correct things....and plz dont misguide

View Tutorial          By: amit verma at 2015-02-19 08:44:55

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by aathishankaran
Web Security Issues
The Web User's Perspective
Server-side plug-Ins
The best way to avoid security vulnerabilities with new server
JavaScript Security
Window Object
Working with Status Bar Messages
Retrieving a Portion of a String
Referencing Windows
Math Object
Frame Object
Document Object
Closing Windows
Built-in Object in Javascript
Textarea Object

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
Using StringTokenizer in Java
The Basic Structure of a Simple Java program
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java