Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip a Hex String

Acording to a other question made here Split a Hex String without spaces and flip it, I write this new question more clearly here.

I have an Hex String like this:

Hex_string = 2B00FFEC

What I need is to change the order of the Hex String to start from the latest characters, so this would be like this:

Fliped_hex_string = ECFF002B

In the other question I asked a way to achieve this using the .split() method. But there should be another way to get this in a better way.

like image 555
masmic Avatar asked Sep 16 '13 14:09

masmic


People also ask

What is the hex value stored for for 2byte integer?

The hex should then be 29(base16) and 49(base16) respectively.

What is hexadecimal code?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.

How do you reverse a hexadecimal value?

Efficient approach: The idea is to use shift operators only. Move the position of the last byte to the first byte using left shift operator(<<). Move the position of the first byte to the last byte using right shift operator(>>). Move the middle bytes using the combination of left shift and right shift operator.


2 Answers

As simple as you can is

    String s = "2B00FFEC";
    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());   //op :ECFF002B
like image 111
Suresh Atta Avatar answered Oct 11 '22 15:10

Suresh Atta


OP constrains the character length to exactly 8 characters in comments.

A purely numeric answer (inspired from idioms to convert endianness); saves going to and from strings

n is an int:

int m = ((n>>24)&0xff) |       // byte 3 to byte 0
        ((n<<8)&0xff0000) |    // byte 1 to byte 2
        ((n>>8)&0xff00) |      // byte 2 to byte 1
        ((n<<24)&0xff000000);  // byte 0 to byte 3

If you need to convert this to hexadecimal, use

String s = Integer.toHexString(m);

and if you need to set n from hexadecimal, use

int n = (int)Long.parseLong(hex_string, 16);

where hex_string is your initial string. You need to go via the Long parser to allow for negatives.

like image 26
Bathsheba Avatar answered Oct 11 '22 13:10

Bathsheba