# Big endian and Little Endian, how to code for reversing binary value?

1. Oct 18, 2011

### MexterO

1. The problem statement, all variables and given/known data

I am trying to create a program that will convert big endian to little endian notation and vice versa. I found a way to represent unsigned integers and display their binary value. Can I use this program somehow to accomplish my goals. I am going the right way?

2. Relevant equations

#include <stdio.h>
#include <stdlib.h>
void displayBits (unsigned value);

int main(void)
{
unsigned x; // will hold number to turn to binary
printf("Enter an unsigned integer: ");
scanf ("%u",&x); // memory address of x state as &x
displayBits(x);

}

void displayBits(unsigned value)
{
unsigned c;

printf("%u = ",value);
for (c=1;c<=32;c++){
putchar(value & displayMask ? '1':'0'); //
value <<=1;
}
putchar ('\n');
}

3. The attempt at a solution

I found a program in my c book on how to do bitwise operators in c. I found the following program. I don't get the for loop totally.

Things I do get:
I get the put char statement and that it will AND the binary value of variable value and displayMask.

I also notice that it will print 1 if condition (value & displayMask) evaluates to true and print 0 if its false. Since there is no new line on the prints statement it is effectively "writing" the binary value of value after the equal sign.
Things I don't get:
I don't however get what value <<=1

and unsigned displayMask = 1<<32 does? I don't see how you can assign a shift operation to a unsigned integer variable?

2. Oct 19, 2011

### Staff: Mentor

When your post includes code, put [ code ] and [ /code ] tags around it (omit the extra spaces, though).
In C and C++ << is the left shift operator. Similarly, >> is the right shift operator. You can combine shifting and assignment with the <<= operator.

In your example above, all of the bits in value get shifted one place to the left, and this new value is assigned to the value variable. For example, if value == 5, its bit pattern looks like this 0000 ... 0000 0101.
Shifting the bits one place to the right results in 0000 ... 0000 1010 (which is decimal 10), and this is the value that is stored in the variable. You might notice that we ended up with a value twice as big as what we started with, and this is not an accident. A left shift of one place is equivalent to multiplying by 2; a left shift of two places is equivalent to multiplying by 22, and so on.
This starts with 1, and shifts it 32 positions to the left. However, if the unsigned type is 32 bits, this operation will shift the 1 off the end of the displayMask variable, resulting in 32 bits of zeroes.