{"id":13672,"date":"2021-10-01T10:30:39","date_gmt":"2021-10-01T05:00:39","guid":{"rendered":"https:\/\/python-programs.com\/?p=13672"},"modified":"2021-11-22T18:33:28","modified_gmt":"2021-11-22T13:03:28","slug":"python-program-to-swap-all-odd-and-even-bits-of-a-number","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-swap-all-odd-and-even-bits-of-a-number\/","title":{"rendered":"Python Program to Swap all Odd and Even Bits of a Number"},"content":{"rendered":"

Given a number, the task is to swap all odd and even bits of the given number in Python.<\/p>\n

In binary, the number 185 is represented as 10111001. The bits in bold are in even positions, and they are 1 1 1 0<\/strong>, while the bits in odd positions are 0 1 0 1<\/strong>.<\/p>\n

After swapping the odd and even bits, we get 118(1110110)<\/p>\n

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

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

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

Given Number =456<\/pre>\n

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

The original given number is = 456\r\nThe modified number after swapping bits is = 708<\/pre>\n

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

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

Given Number =185<\/pre>\n

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

The original given number is = 185\r\nThe modified number after swapping bits is = 118<\/pre>\n

Program to Swap all Odd and Even Bits of a Number in Python<\/h2>\n

Below are the ways to swap all odd and even bits of the given number in Python.<\/p>\n