Bit Basics

Bits are basically represented in either 1 or 0 so the each bit contains either of the 2 values

1

For integer which can hold 32 bits = 4 bytes

Integer max value
Decimal:  2147483648 – (2 power 31)
Binary: 10000000     00000000     00000000     00000000
Integer min value
Decimal: 2147483647 – (2 power 31) – 1
Binary: 11111111     11111111     11111111     11111111
Following table will help to visualize bits in detail
1
This code will give compile error
byte ch = 129; // byte will hold upto 127
No need to cast explicitly to change byte to int
int x = ch;
x = 2000; // now x can hold upto 2147483648
 you need explicit casting to change integer to byte and you will loose data
int x = 2000;
byte ch = (byte) x; // will reduce the value 2000 to 127;
Left Shift (<<)
  •  It is a bit wise operation which will let you shift the bit position.
  • We use this << operator for moving the bit to the position.
  • Left shift is equivalent to the number multiplied by 2
In the below table we move the ‘1’ from the least significant bit(LSB) to the position specified
 1
Right Shift (>>)
  • This is opposite the left shift where we move the bit to right
  • It is equivalent to dividing the number by 2

1.png

Bitwise AND (&)
This will do the AND operation at the bit level. The following code will check number of bits set for the given number
    int x = 65;
    int count= 0;
    while(x>0){
         x = x & (x - 1);
         count ++;
    }
Bitwise OR (|)
This will do the OR operation at the bit level. The following code will check if a bit is set at the given position
    int x = 8;
    int position = 3;
    int mask = 1 << position;
    System.out.println(x | mask);
Bitwise NOT (~)
This operator will help to clear a bit.
    int x = 8;
    int position = 3;
    int mask = 1 << position;
    System.out.println(x & ~mask);
Bitwise XOR (^)
We can use the XOR operator to toggle a bit.
   int x = 8;
   int position = 3;
   int mask = 1 << position;
   System.out.println(x ^ mask);
1 comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: