Skip to content

Commit 30ca324

Browse files
author
Deepak Malik
committed
Bit manipulation
1 parent 5bbe5e2 commit 30ca324

File tree

3 files changed

+205
-0
lines changed

3 files changed

+205
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* Algorithms-in-Java
3+
* BitsConversion.java
4+
*/
5+
package com.deepak.algorithms.BitManipulation;
6+
7+
/**
8+
* Class to hold methods to convert byte to binary and int to binary
9+
* @author Deepak
10+
*/
11+
public class BitsConversion {
12+
13+
14+
15+
}
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/**
2+
* Algorithms-in-Java
3+
* CommonOperations.java
4+
*/
5+
package com.deepak.algorithms.BitManipulation;
6+
7+
/**
8+
* Collection of some common operations on bits
9+
*
10+
* @author Deepak
11+
*/
12+
public class CommonOperations {
13+
14+
/**
15+
* Returns the bit present at the position, either true(1) or false(0)
16+
*
17+
* @param num - Number
18+
* @param i - Position, from which bit has to be fetched
19+
* @return {@link boolean} - True, if 1 is there on position, else false
20+
*/
21+
public static boolean getBit(int num, int i) {
22+
return ((num & (1 << i)) != 0);
23+
}
24+
25+
/**
26+
* Returns the number after updating the bit to either 0 or 1
27+
*
28+
* @param num - Number
29+
* @param i - Position, for which bit has to be updated
30+
* @param v - Value of new bit
31+
* @return {@link int} - New updated number
32+
*/
33+
public static int updateBit(int num, int i, int v) {
34+
int mask = ~(1 << i);
35+
return (num & mask) | (v << i);
36+
}
37+
38+
/**
39+
* Returns the number after setting the bit to 1 at given position
40+
* If bit at that position is already 1, then it returns the same number
41+
*
42+
* @param num - Number
43+
* @param i - Position for which bit has to be set
44+
* @return {@link int} - New updated number
45+
*/
46+
public static int setBit(int num, int i) {
47+
return num | (1 << i);
48+
}
49+
50+
/**
51+
* Returns the number after clearing the bit at given position i.e setting the bit to 0
52+
* If bit at that position is already 0, then it returns the same number
53+
*
54+
* @param num - Number
55+
* @param i - Position for which bit has to be cleared
56+
* @return {@link int} - New updated number
57+
*/
58+
public static int clearBit(int num, int i) {
59+
int mask = ~(1 << i);
60+
return num & mask;
61+
}
62+
63+
public static int clearBitsMSBthroughI(int num, int i) {
64+
int mask = (1 << i) - 1;
65+
return num & mask;
66+
}
67+
68+
public static int clearBitsIthrough0(int num, int i) {
69+
int mask = ~((1 << (i + 1)) - 1);
70+
return num & mask;
71+
}
72+
73+
/**
74+
* Prints the full binary number in String format
75+
*
76+
* @param num - Number
77+
*/
78+
private static void toFullBinaryString(int num) {
79+
/* Create a display mask on the last bit */
80+
int displayMask = 1 << 7;
81+
/* Loop through all the bits and print accordingly */
82+
for (int bit = 1; bit <= 8; bit++) {
83+
System.out.print((num & displayMask) == 0 ? '0' : '1');
84+
num <<= 1;
85+
/* Create space after 4 bits */
86+
if ((bit % 4) == 0) {
87+
System.out.print(' ');
88+
}
89+
}
90+
}
91+
92+
/**
93+
* Dealing with 8 bit representation to make it simple
94+
* @param args
95+
*/
96+
// TODO : Clean this up
97+
public static void main(String[] args) {
98+
int number = 21;
99+
System.out.println("Testing with number: " + number);
100+
toFullBinaryString(number);
101+
102+
/* Get bit */
103+
System.out.println();
104+
System.out.println("\nGet Bit (Original)");
105+
for (int i = 7; i >= 0; i--) {
106+
int res = getBit(number, i) ? 1 : 0;
107+
System.out.print(res);
108+
if ((i % 4) == 0) {
109+
System.out.print(' ');
110+
}
111+
}
112+
113+
/* Set bit */
114+
System.out.println("\n\nSetting Bit at position 3");
115+
int res1 = setBit(number, 3);
116+
toFullBinaryString(res1);
117+
118+
/* Update Bit */
119+
System.out.println("\n\nUpdating Bit at position 2 with 0");
120+
int result = updateBit(number, 2, 0);
121+
toFullBinaryString(result);
122+
123+
/* Clear Bit */
124+
System.out.println("\n\nClearing Bit at position 0");
125+
int clearedBitResult = clearBit(number, 0);
126+
toFullBinaryString(clearedBitResult);
127+
128+
/**/
129+
int number1 = 255;
130+
System.out.println("\n\nBinary representation of " + number1);
131+
toFullBinaryString(number1);
132+
System.out.println("\nClear bits MSB through 4");
133+
int num3 = clearBitsMSBthroughI(number1, 4);
134+
toFullBinaryString(num3);
135+
136+
137+
int number2 = 255;
138+
System.out.println("\n\nBinary representation of " + number2);
139+
toFullBinaryString(number2);
140+
System.out.println("\nClear bits 3 through 0");
141+
int num4 = clearBitsIthrough0(number2, 3);
142+
toFullBinaryString(num4);
143+
144+
}
145+
146+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
## Introduction to Bit Manipulation
2+
3+
The direct manipulation of bits or often called as **Bit twiddling** is often necessary while building softwares.
4+
5+
**Bitwise Operators**
6+
- Individual and blocks of bits in _integer_ and _byte_ variables can be modified with bitwise operators, which are,
7+
8+
<img width="361" alt="screen shot 2016-10-08 at 5 28 24 pm" src="https://cloud.githubusercontent.com/assets/3439029/19216713/aee07c52-8d7c-11e6-8e7a-7af27705be7a.png">
9+
10+
**Bitwise AND**
11+
This is represented as single ampersand, **&** and marks a resulting bit as _1_ when both the bits are _1_. Think about it as _THIS_ **AND** _THIS_ has to be 1 i.e both has to be true. Here is a sample,
12+
```
13+
01001000 &
14+
10111000 =
15+
--------
16+
00001000
17+
```
18+
19+
**Bitwise OR**
20+
This is represented as single pipe symbol, **|** and marks a resulting bit as _1_ when either of the bits is _1_. Think about it as _THIS_ **OR** _THIS_ has to be 1 i.e one of them has to be true. Here is a sample,
21+
```
22+
01001000 |
23+
10111000 =
24+
--------
25+
11111000
26+
```
27+
28+
**Bitwise Exclusive OR (XOR)**
29+
This is represented as, **^** and marks a resulting bit as _1_ when either of the bits is _1_ but NOT if both are. XOR of 2 same bits is 0. Here is a sample,
30+
```
31+
01110010 ^
32+
10101010
33+
--------
34+
11011000
35+
```
36+
Suppose, we have some bit, either 1 or 0, that we'll call Z. When we take Z XOR 0, then we always get Z back: if Z is 1, we get 1, and if Z is 0, we get 0. On the other hand, when we take Z XOR 1, we flip Z. If Z is 0, we get 1; if Z is 1, we get 0:
37+
38+
**myBits ^ 0** : No change
39+
**myBits ^ 1** : Flip
40+
It's a kind of selective twiddle(~)..
41+
So, if we do XOR against 111...1111, all the bits of myBits flipped. It's equivalent of doing twiddle(~)..
42+
43+
Another interesting trick using the XOR: It does in place swap of integers.
44+
If we apply the XOR operation twice -- say we have a bit, A, and another bit B, and we set C equal to A XOR B, and then take C XOR B: we get A XOR B XOR B, which essentially either flips every bit of A twice, or never flips the bit, so we just get back A. (We can also think of B XOR B as cancelling out.)

0 commit comments

Comments
 (0)