-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitwise Operations.cpp
More file actions
130 lines (107 loc) · 2.42 KB
/
Bitwise Operations.cpp
File metadata and controls
130 lines (107 loc) · 2.42 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
void printNum(int a);
void printBinary(int a);
void minBit(int a);
void maxBit(uint8_t a);
void getNBit(int a, int n);
void countValue(int a);
void twoComplement(int a);
int main()
{
int b = 0;
int n = 0;
printf("Enter a number between 0 & 255: ");
scanf("%d", &b);
printf("Choose an n-th digit: ");
scanf("%d", &n);
printf("\n");
//Get the n-te Bits?
getNBit(b, n);
//Print Number
printNum(b);
//Exercises
minBit(b);
maxBit(b);
//Count the Zeros and Ones
countValue(b);
//Two´s Complement
twoComplement(b);
}
void minBit(int a) {
uint8_t min = 0b00000001;
if (a & min) {
printf("LSB: The Number have a min Bit!\n");
}
else {
printf("LSB: The Number have no min Bit!\n");
}
}
void maxBit(uint8_t a) {
uint8_t max = 0b00000001;
max = max << 7;
if (a & max) {
printf("MSB: The Number have a max Bit!\n");
}
else {
printf("MSB: The Number have no max Bit!\n");
}
printf("\n");
}
//Print Number in Decimal, Hexa, Octal & Binary
void printNum(int a) {
printf("Decimal: %d\n", a);
printf("Hexadecimal: %x\n", a);
printf("Octal: %o\n", a);
printf("Binary: ");
printBinary(a);
printf("\n");
}
void printBinary(int a) {
for (int i = 0; i < 8; i++) {
if (a & 0b10000000) {
printf("1");
}
else {
printf("0");
}
a = a << 1;
}
printf("\n");
}
void getNBit(int a, int n) {
uint8_t pos = 0b00000001;
pos = pos << n;
int result = a & pos;
// Get specific value
// a = a >> n;
// a = a & pos;
printf("The position of the n-th is: ");
printBinary(pos);
printf("The result of the n-th is: ");
printBinary(result);
printf("\n");
}
void countValue(int a) {
uint8_t pos = 0b00000001;
int countOne = 0;
int countZero = 0;
for (int i = 0; i < 8; i++) {
if (a & pos) {
countOne++;
}
else {
countZero++;
}
a = a >> 1;
}
printf("Ones: %d, Zeros: %d", countOne, countZero);
printf("\n");
}
void twoComplement(int a) {
uint8_t binary = 0b00000001;
a = ~a;
a = a + binary;
printf("Twos Complement: ");
printBinary(a);
}