reverse hex number

how can i make a swap function which reverses the hex number for example:

input :0x 12 34 51 38
output :0x 38 51 34 12

i can swap numbers 2 at a time but problem is with the presence of 0x..

thanks !!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void swap(unsigned long & val) {
    val = ((val << 24) & 0xFF000000) |
          ((val <<  8) & 0x00FF0000) |
          ((val >>  8) & 0x0000FF00) |
          ((val >> 24) & 0x000000FF);
}

int main() {
    unsigned long a = 0;

    std::cin >> std::hex >> a;
    swap(a);
    std::cout << std::endl << "0x" << std::hex << a << std::endl;

    system("pause");

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <algorithm> //swap()
using namespace std;

string reverse (string s1) {
	int i=2, lli = s1.length();		
	for(;i<lli;i++,lli--)
		swap (s1[i],s1[lli-1]);	//
	return s1;
}

int main() {
		
	string s = "0x72b56e8"; // cin >> s;
	s = reverse (s);	
	cout << s <<endl;
	
	return 0;
}
You guys are helpful and all, but don't you think that it would be better not to just hand out the code and help the OP learn how to do it himself?
Topic archived. No new replies allowed.