Program Discussion :: Bitwise Operator
22 / 15
Write an efficient program to reverse the given binary number
Answer:
#include
#include
using namespace std;
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0, i, temp;
for (i = 0; i < NO_OF_BITS; i++)
{
temp = (num & (1
Asked In ::
Language:
Monika Singh
15 Jun, 2017 10:12 AM
<!DOCTYPE html>
<html>
<body>
<?php
function Bin_rev() {
//input no who decimal equivalent to be calculate
$bin_no = "010111";
echo "Binary no which have to be reverse : " . $bin_no."<br/>";
echo "reversed binary no is:" . strrev($bin_no ) ;
}
// function calling
Bin_rev() ;
?>
</body>
</html>
Language:
Lokeshwari
7 Jul, 2017 9:30 AM
#include <stdio.h>
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0, i, temp;
for (i = 0; i < NO_OF_BITS; i++)
{
temp = (num & (1 << i));
if(temp)
reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
}
return reverse_num;
}
/* Driver function to test above function */
int main()
{
unsigned int x = 2;
printf("%u", reverseBits(x));
getchar();
}
Language:
Nikhil
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include<iostream>
using namespace std;
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0, i, temp;
for (i = 0; i < NO_OF_BITS; i++)
{
temp = (num & (1 << i));
if(temp)
reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
}
return reverse_num;
}
/* Driver function to test above function */
int main()
{
unsigned int x = 2;
printf("%u", reverseBits(x));
getchar();
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.io.*;
public class ReverseBinaryNumber
{
public static int reverse(int num)
{
int reverse=0;
while(num>0)
{
reverse<<=1;
if((int)(num & 1)==1)
reverse=reverse^1;
num>>=1;
}
return reverse;
}
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int num=Integer.parseInt(br.readLine());
System.out.println(reverse(num));
}
}