Hexadecimal numbers in reverse

0

How to print the hexadecimal numbers entered by the user in reverse? For example:

Entrada: 0x101c4701
Saída:   01471C10

If possible in Java and C ++.

In fact I want to get the information contained within a Windows registry file that looks like this:

"0000"=hex:0x001c2701
"0001"=hex:0x001d2701

I wanted a code that would only take 0x001c2701 and invert it to: 01271c00 the code you provided me works, but I would have to copy one by one and how many would be laborious.

    
asked by anonymous 29.11.2014 / 16:28

2 answers

2

In Java you can do it this way:

String input = "0x101c4701";
String result = "";

for (int i = input.length(); i > 3; i -= 2) {
    result += input.substring((i - 2), i);
}

System.out.println(result);
    
29.11.2014 / 16:40
3

Essentially you can use the same solution for both.

int numero = 0x101c4701;
int invertido swapped = ((numero >> 24) & 0xff) | // move byte 3 p/ byte 0
                        ((numero << 8) & 0xff0000) | // move byte 1 p/ byte 2
                        ((numero >> 8) & 0xff00) | // move byte 2 p/ byte 1
                        ((numero << 24) & 0xff000000) // byte 0 p/ byte 3

This is the principle of inversion. Since you did not put the code of what you already did, I do not know what else you might need.

Here's how to convert with Integer.toHexString() and the Long.parseLong() .

If you want to invert a string , it would look something like this in Java:

String s = "101c4701";
StringBuilder result = new StringBuilder();
for (int i = 0; i <=s.length()-2; i=i+2) {
    result.append(new StringBuilder(s.substring(i,i+2)).reverse());
 }
System.out.println(result.reverse().toString());

I placed GitHub for future reference .

As this answer in SO .

And in C ++:

std::string reverse_pairs(std::string const & src) {
    assert(src.size() % 2 == 0);
    std::string result;
    result.reserve(src.size());
    for (std::size_t i = src.size(); i != 0; i -= 2) {
        result.append(src, i - 2, 2);
    }
    return result;
}

I placed GitHub for future reference .

As this answer in SO .

    
29.11.2014 / 16:36