# Bit Basics

Bits are basically represented in either 1 or 0 so the each bit contains either of the 2 values 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 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 Right Shift (>>)
• This is opposite the left shift where we move the bit to right
• It is equivalent to dividing the number by 2 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;
```    int x = 8;
```   int x = 8;