- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang program to check if k’th bit is set for a given number or not.
Examples
Consider n = 20(00010100), k = 3
So, the result after turning off the 3rd bit => 00010000 & (1 << (4-1)) != 0
Approach to solve this problem −
Step 1 − Define a method, where n and k would be the arguments, returns type is int.
Step 2 − Perform AND operation with n & (1<<(k-1)).
Step 3 − If obtained number is not 0 then Kth of n is set else not set.
Example
package main import ( "fmt" "strconv" ) func CheckKthBitSet(n, k int) int { return n & (1 << (k-1)) } func main(){ var n = 20 var k = 3 fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2)) flag := CheckKthBitSet(n, k) if flag !=0 { fmt.Printf("%d rd bit of %d is aleady set.\n", k, n) } else { fmt.Printf("%d rd bit of %d is not set.\n", k, n) } }
Output
Binary of 20 is: 10100. 3 th bit of 20 is aleady set.
- Related Articles
- Golang Program to check a given number is finite or not
- Golang program to turn off the k’th bit in a number.
- Golang Program to turn on the k’th bit in a number.
- Write a Golang program to check whether a given number is prime number or not
- 8085 program to check whether the given 16 bit number is palindrome or not
- Write a Golang program to check whether a given number is a palindrome or not
- Swift Program to Check if the given number is Perfect number or not
- Golang Program to check if the binary representation of a number is palindrome or not
- Golang Program to check the given string is empty or not
- Swift Program to check a given number is finite or not
- Haskell Program to check a given number is finite or not
- Swift Program to Check If a Number is Spy number or not
- C# Program to check if a number is prime or not
- Python program to check if a number is Prime or not
- PHP program to check if a number is prime or not

Advertisements