Last active
January 10, 2018 06:39
-
-
Save TommyJerryMairo/4d59c2805c3c04ad744a78ff4d63cfdc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstdio> | |
#include<unistd.h> | |
#include<getopt.h> | |
using namespace std; | |
int reverse(int); | |
void help(char *); | |
void big2lettle(int); | |
void lettle2big(int); | |
int main(int argc, char * argv[]) { | |
bool reversed = false; | |
char c; | |
while((c=getopt(argc,argv,"r"))!=-1) { | |
switch(c) { | |
case 'r': | |
reversed = true; | |
break; | |
case '-': | |
goto breakpoint; | |
case '?': | |
help(argv[0]); | |
break; | |
default: | |
abort(); | |
} | |
} | |
breakpoint: | |
if(argv[optind]==NULL) | |
help(argv[0]); | |
else { | |
int x=atoi(argv[optind]); | |
if(reversed) lettle2big(x); | |
else big2lettle(x); | |
} | |
return 0; | |
} | |
void help(char * filename) { | |
cout << "Usage: " << filename << " [-r] [--] integer" << endl; | |
cout << "Convert a number from Big-endian to Small-endian, vise versa." << endl; | |
cout << " -- Separator for options and negative integer argument." << endl; | |
cout << " -r Convert from Small-endian to Big-endian." << endl; | |
} | |
void big2lettle(int orig) { | |
int converted = reverse(orig); | |
cout << "Origional: " << orig << endl; | |
printf("Big-endian: 0x%08X\n",orig); | |
printf("Little-endian: 0x%08X\n",converted); | |
cout << "Converted: " << converted << endl; | |
return; | |
} | |
void lettle2big(int orig) { | |
int converted = reverse(orig); | |
cout << "Origional: " << orig << endl; | |
printf("Lettle-endian: 0x%08X\n",converted); | |
printf("Big-endian: 0x%08X\n",orig); | |
cout << "Converted: " << converted << endl; | |
return; | |
} | |
int reverse(int orig) { | |
int res=0; | |
for(int i=0; i<4; i++) { | |
int byte=orig&0xff; | |
int shifted=byte<<(3-i)*8; | |
res|=shifted; | |
orig>>=8; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment