-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bit_manipulation.java
98 lines (78 loc) · 2.25 KB
/
Bit_manipulation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
public class Bit_manipulation {
public static String oddOrEven(int n){
int bitmask = 1;
if ((n&bitmask) == 0){
return n + " is Even";
}
return n + " is Odd";
}
public static int get_ith_bit(int n, int i){
int bitmask = 1<<i; // Left shift till the position
if ((n&bitmask) == 0){
return 0;
}
return 1;
}
public static int set_ith_bit(int n, int i){
int bitmask = 1<<i;
return n | bitmask;
}
public static int clear_ith_bit(int n, int i){
int bitmask = 1<<i;
return n & ~(bitmask);
}
// Update the ith bit to newbit : 1 or 0
public static void update_ith_bit(int n, int i, int newbit){
if (newbit == 1){
clear_ith_bit(n, i);
}else {
set_ith_bit(n,i);
}
}
// clear last i bits
public static int clear_last_ith_bits(int n, int i){
int bitmask = (~0)<<i;
return n & bitmask;
}
// Check if the number is power of 2
public static boolean power_of_two(int n){
return ((n&(n-1)) == 0);
}
// Count set bits
public static int count_set_bit(int n){
int count = 0;
while (n>0){
if ((n&1) != 0){
count++;
}
n = n >> 1;
}
return count;
}
// Fast Exponentiation : a^n
public static int fast_exponent(int a, int n){
int ans = 1;
while (n>0){
if ((n&1)!=0){
ans = ans * a;
}
a = a*a;
n = n>>1;
}
return ans;
}
public static void main(String[] args) {
String ans = oddOrEven(11);
System.out.println(ans);
ans = oddOrEven(12);
System.out.println(ans);
int position = get_ith_bit(10, 3);
System.out.println(position);
int res = set_ith_bit(10, 2);
System.out.println(res);
System.out.println(clear_ith_bit(10, 3));
System.out.println(power_of_two(6));
System.out.println(count_set_bit(1));
System.out.println(fast_exponent(3, 3));
}
}