{"id":20531,"date":"2021-09-15T19:50:44","date_gmt":"2021-09-15T14:20:44","guid":{"rendered":"https:\/\/python-programs.com\/?p=20531"},"modified":"2021-11-22T18:36:18","modified_gmt":"2021-11-22T13:06:18","slug":"python-program-to-toggle-the-last-m-bits","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-toggle-the-last-m-bits\/","title":{"rendered":"Python Program to Toggle the Last m Bits"},"content":{"rendered":"

In the previous article, we have discussed Python Program to Count Minimum Bits to Flip such that XOR of A and B Equal to C<\/a><\/p>\n

Given a number n, the task is to toggle the last m bits of the given number in its binary representation.<\/p>\n

Toggling:\u00a0<\/strong><\/p>\n

A toggling operation changes the value of a bit from 0 to 1 and from 1 to 0.<\/p>\n

let Given number =30 m=3<\/p>\n

The binary representation of 30=11110<\/p>\n

Binary representation after toggling the last 3 bits is =11001<\/p>\n

Decimal equivalent after toggling =25<\/p>\n

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

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

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

Given Number = 30\r\nGiven m value =  3<\/pre>\n

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

The given number{ 30 } after toggling the given last m { 3 } bits =  25<\/pre>\n

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

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

Given Number = 45\r\nGiven m value =  2<\/pre>\n

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

The given number{ 45 } after toggling the given last m { 2 } bits =  46<\/pre>\n

Program to Toggle the Last m Bits in Python<\/h2>\n

Below are the ways to toggle the given last m bits of a given number in python:<\/p>\n