Salutations All,,,

Just looking for some input on this C program..:?:


I believe it is working correctly but I think I have my Understanding
of bits backWards....... :hair:


AnyWho - The program should input a value from user and call the reversebit
function to print the bits in both original and reverse order....

Thanks for the input,,,,,,

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <math.h>

int reversebits( unsigned int n ); /* prototype */

int reversebits(unsigned int n)
{
	unsigned int temp = n;
	int i;

	for(i = (sizeof(n) *8-1 ); i ; i--)
	{
	temp = temp | (n & 1);
	temp = temp <<1;
	n = n >>1;
	}
	temp = temp | (n & 1);

	return temp;
}

void main()
{
	int number;
	int reversednumber;
	int i;
	int temp;

	printf("\nEnter the number: ");
	scanf("%d", &number);

	reversednumber = reversebits(number);

	printf("\n\n\nBits in the original number:\n\n");
	for( i = 0; i < 32; i++)
	{
		temp = number >> i & 1;
		printf("%d ",temp);
	}

	printf("\n\n\n\nBits in the reverse order:\n\n");

	for( i = 0; i < 32; i++ )
	{
		temp = (reversednumber >> i ) & 1;
		printf("%d ",temp);
	}
	getch();
}

Look at how I displayed the binary number...its much easier to read, besides that the code code looks O.K.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int reversebits( unsigned int n ); /* prototype */

int reversebits(unsigned int n)
{
	unsigned int temp = n;
	int i;

	for(i = (sizeof(n) *8-1 ); i ; i--)
	{
	temp = temp | (n & 1);
	temp = temp <<1;
	n = n >>1;
	}
	temp = temp | (n & 1);

	return temp;
}

int main()
{
	int number;
	int reversednumber;
	int i;
	int temp;

	printf("\nEnter the number: ");
	scanf("%d", &number);

	reversednumber = reversebits(number);

	printf("\n\n\nBits in the original number:\n\n");
	for( i = 0; i < 32; i++)
	{
		if (0 == i % 4) fputc(' ', stdout);
		temp = number >> i & 1;
		printf("%d ",temp);
	}

	printf("\n\n\n\nBits in the reverse order:\n\n");

	for( i = 0; i < 32; i++ )
	{
		if (0 == i % 4) fputc(' ', stdout);
		temp = (reversednumber >> i ) & 1;
		printf("%d ",temp);
	}
       fputs("\n", stdout);
	exit(EXIT_SUCCESS);
}

Edited 6 Years Ago by gerard4143: n/a

I believe it is working correctly but I think I have my Understanding
of bits backWards....... :hair:

When you print the bits of the number, I would presume you want to print MSB to LSB so it reads from left to right. By printing from LSB to MSB, it reads from right to left, which I find confusing. I might print the bits like this. Also, other methods for reversing bits are here.

This question has already been answered. Start a new discussion instead.