{"id":20370,"date":"2021-09-11T15:37:55","date_gmt":"2021-09-11T10:07:55","guid":{"rendered":"https:\/\/python-programs.com\/?p=20370"},"modified":"2021-11-22T18:36:22","modified_gmt":"2021-11-22T13:06:22","slug":"python-program-to-get-nth-bit-of-a-number","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-get-nth-bit-of-a-number\/","title":{"rendered":"Python Program to Get nth Bit of a Number"},"content":{"rendered":"

In the previous article, we have discussed Program to Find All Non Repeated Characters in a String<\/a><\/p>\n

Given a number and the bit position, the task is to get the bit that is present at that position (in the binary representation of a number).<\/p>\n

Bitwise & Operator:<\/strong><\/p>\n

If both bits are 1, sets each bit to 1.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given Number = 2\r\nBit position(in range 0-31)= 0<\/pre>\n

Output:<\/strong><\/p>\n

The bit present at the given position{ 0 } for a given number is 0<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given Number = 14\r\nBit position(in range 0-31)= 3<\/pre>\n

Output:<\/strong><\/p>\n

The bit present at the given position{ 3 } for a given number is 1<\/pre>\n

Program to Get nth Bit of a Number in Python<\/h2>\n

Below are the ways to get the bit that is present at that position (in the binary representation of a number) in python:<\/p>\n