From db436e079a4cb712238c9271d3f0b3c1f0ae5d00 Mon Sep 17 00:00:00 2001 From: Emmanuel Hernandez Date: Tue, 24 Jan 2023 13:50:43 -0600 Subject: [PATCH] write function to get ith bit in cpp --- Bit-manipulationTechniques/GetIthBit/main.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Bit-manipulationTechniques/GetIthBit/main.cpp diff --git a/Bit-manipulationTechniques/GetIthBit/main.cpp b/Bit-manipulationTechniques/GetIthBit/main.cpp new file mode 100644 index 0000000..5cf5520 --- /dev/null +++ b/Bit-manipulationTechniques/GetIthBit/main.cpp @@ -0,0 +1,23 @@ +/* + * Write a function to: + * - get ith bit + */ +#include + +using namespace std; + +int getIthBit(int n, int i) +{ + int mask = 1 << i; + return (n & mask) > 0 ? 1 : 0; +} + +int main() +{ + int i, n = 5; + cin >> i; + + cout << "Bit at " << i << "th position: " << getIthBit(n, i) << endl; + + return 0; +}