#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
/*
* Converts from little to big endian or vice-versa
* Labeling bytes from 0 to 3, left to right, this effectively performs the following swaps:
* 0 <-> 3
* 1 <-> 2
* Thus given a little or big endian unsigned long it will go from 0,1,2,3 to 3,2,0,1 relative to the previously mentioned byte order.
* This swaps the bytes correctly to inter-convert between the two formats.
* The below bit-wise operations perform these swaps.
*/
unsigned long switchEndianess(unsigned long num) {
return (((num&0x000000FF)<<24) + ((num&0xFF000000)>>24)) + ((num&0x0000FF00)<<8) + ((num&0x00FF0000)>>8);
}
/*
* Converts a 32-bit long integer into binary.
*/
void decimalToBinary(unsigned long decimal, char* result) {
int i;
for (i = 31; i >= 0; i--) {
if (((decimal&(1<<i))>>i) == 1) {
strcat(result, "1");
} else {
strcat(result, "0");
}
if ((i % 4) == 0) {
strcat(result, " ");
}
}
return strcat(result, "\0");
}
/*
* Allows a user to convert a 32-bit integer from little to big endian.
* Displays the numbers in binary as well.
*/
int main() {
unsigned long littleEndian;
char littleEndianBinary[32 + 7 + 1];
unsigned long bigEndian;
char bigEndianBinary[32 + 7 + 1];
/* Set the numereic locale to the system default locale */
/*
* Note that this would cause numbers to be printed with thousands seperators on a newer system,
* through the use of the "'" flag for printf.
*/
setlocale (LC_NUMERIC, "");
while(TRUE) {
printf("Enter a natural number to convert from little to big endian: (0 to quit)\n");
/* get input */
scanf("%lu", &littleEndian);
/* break on sentinal */
if (littleEndian == 0) {
break;
}
printf("Converting %'lu to big endian...\n", littleEndian);
littleEndianBinary[0] = '\0';
decimalToBinary(littleEndian, &littleEndianBinary);
printf("The number in little endian binary is: %s\n", littleEndianBinary);
bigEndian = switchEndianess(littleEndian);
bigEndianBinary[0] = '\0';
decimalToBinary(bigEndian, &bigEndianBinary);
printf("The number in big endian binary is: %s\n", bigEndianBinary);
printf("The number in big endian is: %'lu\n", bigEndian);
};
return EXIT_SUCCESS;
}