Flip a Hex String

天大地大妈咪最大 提交于 2019-12-06 12:42:52

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.

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

You could do something like:

String a = "456789AB";
char[] ca = a.toCharArray();
StringBuilder sb = new StringBuilder(a.length());
for (int i = 0; i<a.length();i+=2)
{
  sb.insert(0, ca, i, 2);
}

This also extends to longer Strings if needed

Perhaps you should try something as simple as this:

public static String flip(final String hex){
    final StringBuilder builder = new StringBuilder(hex.length());
    for(int i = hex.length(); i > 1; i-=2)
        builder.append(hex.substring(i-2, i));
    return builder.toString();
}

public static void main(String args[]){
    System.out.println(flip("2B00FFEC"));
}

The output is: ECFF002B

Next time you ask a question, perhaps you should show us some code you've written used in order to solve your problem (and then ask us why your code doesn't work, not your problem). You will not learn anything from us just providing answers without you knowing how they work.

This method seems to do what you want

String changeHexOrder(String s) {
    char[] arr = s.toCharArray();
    char tmp;
    //change positions of [i, i + 1 , , , , , ,length - i - 2, length - i - 1]
    for (int i = 0; i < arr.length / 2; i += 2) {
        tmp = arr[i];
        arr[i] = arr[arr.length-i-2];
        arr[arr.length-i-2] = tmp;

        tmp = arr[i+1];
        arr[i+1] = arr[arr.length-i-1];
        arr[arr.length-i-1] = tmp;
    }
    return new String(arr);
}

This worked for me

    StringBuilder lsbToMsb=new StringBuilder();

    for(int i=input.length();i>0;i-=2)
    {
        lsbMsb.append(lsbToMsb.substring(i-2,i));
    }


    String lsbMsb=lsbMsb.toString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!