开发者社区> 问答> 正文

java怎样实现十六进制字符串高低位转换

比如我有十六进制字符串“2E0A”,怎样转化为“0A2E”?

展开
收起
泡沫小迪 2020-05-29 16:07:07 2059 0
1 条回答
写回答
取消 提交回答
  • 转成char[],然后for循环+交换一下顺序,最后把char[]再转成string。
    @Test
    public void test_reverseHex() {
      Assert.assertEquals("23010A2E", reverseHex("2E0A0123"));
      Assert.assertEquals("2E0A0123", reverseHex(reverseHex("2E0A0123")));
    }
    
    private static String reverseHex(final String hex) {
      final char[] charArray = hex.toCharArray();
      final int length = charArray.length;
      final int times = length / 2;
      for (int c1i = 0; c1i < times; c1i += 2) {
        final int c2i = c1i + 1;
        final char c1 = charArray[c1i];
        final char c2 = charArray[c2i];
        final int c3i = length - c1i - 2;
        final int c4i = length - c1i - 1;
        charArray[c1i] = charArray[c3i];
        charArray[c2i] = charArray[c4i];
        charArray[c3i] = c1;
        charArray[c4i] = c2;
      }
      return new String(charArray);
    }
    
    
    2020-05-29 16:07:17
    赞同 1 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载