Program Discussion :: Bitwise Operator
16 / 15
Write an efficient program to toggle all bits in a given integer number
Answer:
#include
#include
using namespace std;
int main()
{
int num, n, newNum;
/*Reads a number from user*/
coutnum;
/*Reads the bit number you want to toggle*/
coutn;
/* Left shifts 1 to n times then perform bitwise XOR with number and result of above*/
newNum = num ^ (1
Asked In ::
Language:
Jyoti Choudhary
15 May, 2017 12:07 AM
import java.util.*;
import java.lang.*;
import java.io.*;
class toggleAllBits
{
public static void main(String args[])
{
int num; int bit;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number : ");
num = in.nextInt();
bit = Integer.SIZE;
for(int i = 0; i< bit; i++)
{
num = num ^ (1<<i);
}
System.out.println("After toggle number is " +num);
}
}
Language:
Varun
1 Jul, 2017 11:07 PM
<!DOCTYPE html>
<html>
<body>
<?php
function Toggle_no() {
$num=60;
$bit=20;
for( $i = 0; $i< $bit; $i++)
{
$num = $num ^ (1<<$i);
}
echo "After toggle number is ".$num;
}
Toggle_no() ;
?>
</body>
</html>
Language:
Rakool
7 Jul, 2017 9:30 AM
#include <stdio.h>
int main()
{
int num, n, newNum;
//Reads a number from user
printf("Enter any number: ");
scanf("%d", &num);
//Reads the bit number you want to toggle
printf("Enter nth bit to toggle (0-31): ");
scanf("%d", &n);
/* Left shifts 1 to n times then perform bitwise XOR with number and result of above*/
newNum = num ^ (1 << n);
printf("Bit toggled successfully.\n\n");
printf("Number before toggling %d bit: %d (in decimal)\n", n, num);
printf("Number after toggling %d bit: %d (in decimal)\n", n, newNum);
return 0;
}
Language:
Neha
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
int num, n, newNum;
/*Reads a number from user*/
cout<<"Enter any number: ";
cin>>num;
/*Reads the bit number you want to toggle*/
cout<<"Enter nth bit to toggle (0-31): ";
cin>>n;
/* Left shifts 1 to n times then perform bitwise XOR with number and result of above*/
newNum = num ^ (1 << n);
cout<<"Bit toggled successfully.\n\n";
cout<<"Number before toggling %d bit: %d (in decimal)\n", n, num;
cout<<"Number after toggling %d bit: %d (in decimal)\n", n, newNum;
return 0;
}