어떻게 자바 바이트 배열에서 16 진수 문자열이 될 것입니다 변환하는?

인쇄 할 수없는 많은 요소가 있기 때문에 내가 16 진수로 가득하고, 바이트 배열을 인쇄 한 가장 간단한 방법은 의미가 없습니다. 내가 필요한 것은 16 진수 코드의 정확한 형태이다 :3a5f771c


# 1 층

가장 간단한 솔루션, 외부 라이브러리, 숫자하지 상수 :

public static String byteArrayToHex(byte[] a) {
   StringBuilder sb = new StringBuilder(a.length * 2);
   for(byte b: a)
      sb.append(String.format("%02x", b));
   return sb.toString();
}

하우스 # 2

나를 위해 일한 oneliner이 간단한
String result = new BigInteger(1, inputBytes).toString(16);
편집 - 앞에 0을 제거하기 위해이 방법을 사용하지만, 이봐 내 사용 사례에서 일했다. 덕분에 주목 @Voicu


하우스 # 3

// // 변화는보다 효과적으로 당신은 또한 바이트를 사용할 수 있습니다 바이트

public static String getHexString (String s) 
{
    byte[] buf = s.getBytes();

    StringBuffer sb = new StringBuffer();

    for (byte b:buf)
    {
        sb.append(String.format("%x", b));
    }


        return sb.toString();
}

# 4 층

매우 빠르고 간단하며 메모리 룩업 테이블의 소량의 비용.

 private static final char[] BYTE2HEX=(
    "000102030405060708090A0B0C0D0E0F"+
    "101112131415161718191A1B1C1D1E1F"+
    "202122232425262728292A2B2C2D2E2F"+
    "303132333435363738393A3B3C3D3E3F"+
    "404142434445464748494A4B4C4D4E4F"+
    "505152535455565758595A5B5C5D5E5F"+
    "606162636465666768696A6B6C6D6E6F"+
    "707172737475767778797A7B7C7D7E7F"+
    "808182838485868788898A8B8C8D8E8F"+
    "909192939495969798999A9B9C9D9E9F"+
    "A0A1A2A3A4A5A6A7A8A9AAABACADAEAF"+
    "B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF"+
    "C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"+
    "D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"+
    "E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF"+
    "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF").toCharArray();
   ; 

  public static String getHexString(byte[] bytes) {
    final int len=bytes.length;
    final char[] chars=new char[len<<1];
    int hexIndex;
    int idx=0;
    int ofs=0;
    while (ofs<len) {
      hexIndex=(bytes[ofs++] & 0xFF)<<1;
      chars[idx++]=BYTE2HEX[hexIndex++];
      chars[idx++]=BYTE2HEX[hexIndex];
    }
    return new String(chars);
  }

하우스 # 5

javax.xml.bind.DatatypeConverter.printHexBinary()방법이하는 byte[]16 진수 문자열 편리한 방법을 변환, 그것은이다 아키텍처를 바인딩 자바 XML (JAXB)이다 의 일부. DatatypeConverter클래스는 또한 많은 다른 유용한 데이터 처리 방법을 포함한다.

자바 (8) 및 이전 버전에서는 JAXB는 자바 표준 라이브러리의 일부입니다. 모든 Java EE가 자신의 라이브러리의 버전 패키지로 이동하려면 자바 (9) 에서 사용되지 않는 자바 (11)으로 되어 이미 삭제를 . 그것은 긴 이야기 . 지금 javax.xml.bind은 존재하지 않고, 당신이 원하는 경우에 사용이 포함 DatatypeConverterJAXB를, 당신은 메이븐 설치해야 JAXB APIJAXB 런타임 .

사용 예제 :

byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
String hex = javax.xml.bind.DatatypeConverter.printHexBinary(bytes);

발생합니다 :

000086003D

에 대한 답 동일.


하우스 # 6

나는 보통 문 debuf 다음과 같은 방법을 사용하여 수행하지만, 문제는이 작업을 수행 할 수있는 가장 좋은 방법은 나도 몰라

private static String digits = "0123456789abcdef";

public static String toHex(byte[] data){
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i != data.length; i++)
    {
        int v = data[i] & 0xff;
        buf.append(digits.charAt(v >> 4));
        buf.append(digits.charAt(v & 0xf));
    }
    return buf.toString();
}

구축 # 7

나는 이것을 사용하는 것을 선호 :

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes, int offset, int count) {
    char[] hexChars = new char[count * 2];
    for ( int j = 0; j < count; j++ ) {
        int v = bytes[j+offset] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

그것은 약간 허용 대답에 적용된다. 개인적으로 나를 위해, 내가 대답이 과부하 더 허용에 대한 답을 유지, 많은 경우에 사용할 수 있습니다.


구축 # 8

N 16 진수 문자열 시각적으로 함께 결합 될 바이트 출력을 할 수있는 작은 변형이 제안 용액 @maybewecouldstealavan :

 final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
 final static char BUNDLE_SEP = ' ';

public static String bytesToHexString(byte[] bytes, int bundleSize /*[bytes]*/]) {
        char[] hexChars = new char[(bytes.length * 2) + (bytes.length / bundleSize)];
        for (int j = 0, k = 1; j < bytes.length; j++, k++) {
                int v = bytes[j] & 0xFF;
                int start = (j * 2) + j/bundleSize;

                hexChars[start] = HEX_ARRAY[v >>> 4];
                hexChars[start + 1] = HEX_ARRAY[v & 0x0F];

                if ((k % bundleSize) == 0) {
                        hexChars[start + 2] = BUNDLE_SEP;
                }   
        }   
        return new String(hexChars).trim();    
}

즉 :

bytesToHexString("..DOOM..".toCharArray().getBytes(), 2);
2E2E 444F 4F4D 2E2E

bytesToHexString("..DOOM..".toCharArray().getBytes(), 4);
2E2E444F 4F4D2E2E

하우스 # 9

어떻게 이런 일에 대해?

    String byteToHex(final byte[] hash)
    {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

하우스 # 10

정확히 같은 바이트 배열 파이썬을 찾고 있다면 나는이 자바 변환 파이썬을 달성했다.

class ByteArray:

@classmethod
def char(cls, args=[]):
    cls.hexArray = "0123456789ABCDEF".encode('utf-16')
    j = 0
    length = (cls.hexArray)

    if j < length:
        v = j & 0xFF
        hexChars = [None, None]
        hexChars[j * 2] = str( cls.hexArray) + str(v)
        hexChars[j * 2 + 1] = str(cls.hexArray) + str(v) + str(0x0F)
        # Use if you want...
        #hexChars.pop()

    return str(hexChars)

array = ByteArray()
print array.char(args=[])

하우스 # 11

구아바 솔루션의 무결성을 보장하기 위해 :

import com.google.common.io.BaseEncoding;
...
byte[] bytes = "Hello world".getBytes(StandardCharsets.UTF_8);
final String hex = BaseEncoding.base16().lowerCase().encode(bytes);

이제, hex"48656c6c6f20776f726c64".


하우스 # 12

사용 DataTypeConverter 클래스javax.xml.bind.DataTypeConverter

String hexString = DatatypeConverter.printHexBinary(bytes[] raw);


하우스 # 13

음,이 작업을 수행하는 방법에는 여러 가지가 있습니다,하지만 당신은 라이브러리를 사용하기로 결정한다면, 나는 몇 가지 기능이 프로젝트의 일부가되었습니다 라이브러리에 구현되어 있는지 여부를 확인하기 위해, 프로젝트에 대해 자세히 살펴 것을 권장하고 추가 새 라이브러리는 그것을 할 수 있습니다. 예를 들어, 당신이하지 않은 경우

org.apache.commons.codec.binary.Hex

어쩌면 당신은 ...

org.apache.xerces.impl.dv.util.HexBin


하우스 # 14

나는 그런 해시로, 고정 길이 유사한 방법을 사용합니다 :

md5sum = String.format("%032x", new BigInteger(1, md.digest()));

하우스 # 15

  public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
      data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
        + Character.digit(s.charAt(i+1), 16));
    }
  return data;
  } 

하우스 # 16

이것은이다 java.util.Base64없는 아주 예쁜, (부분)의 실현?

public class Base16/*a.k.a. Hex*/ {
    public static class Encoder{
        private static char[] toLowerHex={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        private static char[] toUpperHex={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        private boolean upper;
        public Encoder(boolean upper) {
            this.upper=upper;
        }
        public String encode(byte[] data){
            char[] value=new char[data.length*2];
            char[] toHex=upper?toUpperHex:toLowerHex;
            for(int i=0,j=0;i<data.length;i++){
                int octet=data[i]&0xFF;
                value[j++]=toHex[octet>>4];
                value[j++]=toHex[octet&0xF];
            }
            return new String(value);
        }
        static final Encoder LOWER=new Encoder(false);
        static final Encoder UPPER=new Encoder(true);
    }
    public static Encoder getEncoder(){
        return Encoder.LOWER;
    }
    public static Encoder getUpperEncoder(){
        return Encoder.UPPER;
    }
    //...
}

하우스 # 17

private static String bytesToHexString(byte[] bytes, int length) {
        if (bytes == null || length == 0) return null;

        StringBuilder ret = new StringBuilder(2*length);

        for (int i = 0 ; i < length ; i++) {
            int b;

            b = 0x0f & (bytes[i] >> 4);
            ret.append("0123456789abcdef".charAt(b));

            b = 0x0f & bytes[i];
            ret.append("0123456789abcdef".charAt(b));
        }

        return ret.toString();
    }

하우스 # 18

모든 솔루션은이 페이지가 해결할 수없는에서 찾을 수 없습니다

  1. 루프를 사용하여
  2. 사용 javax.xml.bind.DatatypeConverter 좋은 컴파일 될 수 있지만 자주 실행시 java.lang.NoClassDefFoundError가를 throw 할 수 있습니다.

(I는 다른 결함이 없어야 약속하지만)이 상기 용액의 결함없는

import java.math.BigInteger;

import static java.lang.System.out;
public final class App2 {
    // | proposed solution.
    public static String encode(byte[] bytes) {          
        final int length = bytes.length;

        // | BigInteger constructor throws if it is given an empty array.
        if (length == 0) {
            return "00";
        }

        final int evenLength = (int)(2 * Math.ceil(length / 2.0));
        final String format = "%0" + evenLength + "x";         
        final String result = String.format (format, new BigInteger(bytes));

        return result;
    }

    public static void main(String[] args) throws Exception {
        // 00
        out.println(encode(new byte[] {})); 

        // 01
        out.println(encode(new byte[] {1})); 

        //203040
        out.println(encode(new byte[] {0x20, 0x30, 0x40})); 

        // 416c6c20796f75722062617365206172652062656c6f6e6720746f2075732e
        out.println(encode("All your base are belong to us.".getBytes()));
    }
}   

나는 62 오피 코드에서이 정보를 얻을 수 있지만 미만은 0x10의 첫 번째 바이트를 방지하기 위해 제로 패딩을 사용할 수없는 경우, 다음 솔루션은 23야드를 사용하여 작동합니다. 디스플레이는 기본을 달성하지 않는 경우 (또는이 경우에하는 수 있다면 BigInteger를 제로 접두사 옵션) 등의 달성과 같은 문자열 길이가 홀수 인 경우, 0으로 채워은 "쉬운" "또는 같은 단어, 자신의 "솔루션은 매우 비싼 될 수 있습니다. toString).

public static String encode(byte[] bytes) {          
    final int length = bytes.length;

    // | BigInteger constructor throws if it is given an empty array.
    if (length == 0) {
        return "00";
    }

    return new BigInteger(bytes).toString(16);
}

하우스 # 19

내 솔루션의 힘은 기반 솔루션을 WeCouldStealAVan하지만 할당 된 추가 조회 테이블에 의존하지 않습니다. 그것은 (사실, "문자로 문자에서"어떤 강압을 사용하지 않는 Character.forDigit()이 느려질 수 있습니다, 그래서, 일부는 검사 숫자의 진정한 의미에 비교 않았다). 언제 어디서나 사용하십시오. 건배.

public static String bytesToHex(final byte[] bytes)
{
    final int numBytes = bytes.length;
    final char[] container = new char[numBytes * 2];

    for (int i = 0; i < numBytes; i++)
    {
        final int b = bytes[i] & 0xFF;

        container[i * 2] = Character.forDigit(b >>> 4, 0x10);
        container[i * 2 + 1] = Character.forDigit(b & 0xF, 0x10);
    }

    return new String(container);
}

하우스 # 20

당신이 봄 보안 프레임 워크를 사용하는 경우, 당신은 사용할 수 있습니다 :

import org.springframework.security.crypto.codec.Hex

final String testString = "Test String";
final byte[] byteArray = testString.getBytes();
System.out.println(Hex.encode(byteArray));

하우스 # 21

          Converts bytes data to hex characters

          @param bytes byte array to be converted to hex string
          @return byte String in hex format

        private static String bytesToHex(byte[] bytes) {
            char[] hexChars = new char[bytes.length * 2];
            int v;
            for (int j = 0; j < bytes.length; j++) {
                v = bytes[j] & 0xFF;
                hexChars[j * 2] = HEX_ARRAY[v >>> 4];
                hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
            }
            return new String(hexChars);
        }

하우스 # 22

간단한 함수 항아리 유틸리티는 좋은 선택하지 않습니다 추가합니다. 그러나 오히려 자신의 유틸리티 클래스의 컴파일. 다음은 빠른 구현이 가능하다.

public class ByteHex {

    public static int hexToByte(char ch) {
        if ('0' <= ch && ch <= '9') return ch - '0';
        if ('A' <= ch && ch <= 'F') return ch - 'A' + 10;
        if ('a' <= ch && ch <= 'f') return ch - 'a' + 10;
        return -1;
    }

    private static final String[] byteToHexTable = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
        "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
        "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
        "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
        "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
        "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
        "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
    };

    private static final String[] byteToHexTableLowerCase = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
        "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
        "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
        "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
        "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
        "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
        "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
    };

    public static String byteToHex(byte b){
        return byteToHexTable[b & 0xFF];
    }

    public static String byteToHex(byte[] bytes){
        if(bytes == null) return null;
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTable[b & 0xFF]);
        return sb.toString();
    }

    public static String byteToHex(short[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(short b : bytes) sb.append(byteToHexTable[((byte)b) & 0xFF]);
        return sb.toString();
    }

    public static String byteToHexLowerCase(byte[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTableLowerCase[b & 0xFF]);
        return sb.toString();
    }

    public static byte[] hexToByte(String hexString) {
        if(hexString == null) return null;
        byte[] byteArray = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            byteArray[i / 2] = (byte) (hexToByte(hexString.charAt(i)) * 16 + hexToByte(hexString.charAt(i+1)));
        }
        return byteArray;
    }

    public static byte hexPairToByte(char ch1, char ch2) {
        return (byte) (hexToByte(ch1) * 16 + hexToByte(ch2));
    }


}

하우스 # 23

여기에 (큰 라이브러리) 복잡한 간단한 (편도)에서 몇 가지 일반적인 옵션이 있습니다. 성능에 관심이 있다면, 다음과 같은 마이크로 벤치 마크를 참조하십시오.

옵션 1 : 코드 조각 - 간단한

아주 간단한 솔루션을 사용하는 것입니다 BigInteger진수 표현 :

new BigInteger(1, someByteArray).toString(16)

이 접근 방식 때문에주의하시기 바랍니다 디지털 임의 아닌 , 바이트 문자열 은 앞의 0을 생략 할 수 있도록 - 당신이 원하는 것을 할 수있다, 당신이 원하는하지 않을 수 있습니다 (예를 들어, 3 바이트의 입력을위한 000AE3VS 0AE3). 그것은 매우 느린 또한, 다음 옵션은 약에 비해 느리다 100 배 .

옵션 2 : 코드 조각 - 고급

이것은 완전한 기능, 복사 및 스 니펫 지원에 붙여 넣을 수 있습니다 대문자 / 소문자바이트 순서를 . 메모리의 복잡성을 최소화하고, 성능을 향상시키고, 자바의 모든 현대적인 버전 (5+)와 호환해야하는 최적화되었습니다.

private static final char[] LOOKUP_TABLE_LOWER = new char[]{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66};
private static final char[] LOOKUP_TABLE_UPPER = new char[]{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46};

public static String encode(byte[] byteArray, boolean upperCase, ByteOrder byteOrder) {

    // our output size will be exactly 2x byte-array length
    final char[] buffer = new char[byteArray.length * 2];

    // choose lower or uppercase lookup table
    final char[] lookup = upperCase ? LOOKUP_TABLE_UPPER : LOOKUP_TABLE_LOWER;

    int index;
    for (int i = 0; i < byteArray.length; i++) {
        // for little endian we count from last to first
        index = (byteOrder == ByteOrder.BIG_ENDIAN) ? i : byteArray.length - i - 1;

        // extract the upper 4 bit and look up char (0-A)
        buffer[i << 1] = lookup[(byteArray[index] >> 4) & 0xF];
        // extract the lower 4 bit and look up char (0-A)
        buffer[(i << 1) + 1] = lookup[(byteArray[index] & 0xF)];
    }
    return new String(buffer);
}

public static String encode(byte[] byteArray) {
    return encode(byteArray, false, ByteOrder.BIG_ENDIAN);
}

당신은 할 수 있습니다 여기에 완전한 소스 코드를 아파치 v2를 라이센스와 디코더를 가지고 찾을 수 있습니다.

옵션 3 : 작은 최적화 라이브러리 : 바이트 - 자바

프로젝트를 다루고, 나는 자바 바이트에서 처리하기 위해이 작은 도구 키트를 만들었습니다. 그것은 외부 의존성이없고 자바 7 +와 호환됩니다. 특히, 그것은 매우 빠르고 잘 테스트 HEX 인코더 / 디코더을 포함한다 :

import at.favre.lib.bytes.Bytes;
...
Bytes.wrap(someByteArray).encodeHex()

당신은 할 수 Github에서은 에 그것을 확인 자바 바이트 : .

옵션 4 : 아파치 코 몬즈 코덱

물론, 좋은 범용이 일반적인 코덱 . ( 의견 앞 경고 위에 설명 된 프로젝트 중)을, 나는 코드를 분석, 매우 실망했다. 많은 반복 조직적 코드 사용되지 않는 외부 코덱은 거의 오버 설계하지 않을 수와 인기 코덱 (특히 Base64로)의 느린 실현에 유용합니다. 당신이 또는 다른 방법을 사용하고자한다면, 나는 정보통 결정을 내릴 것입니다. 당신은 아직도 그것을 사용하려면 어쨌든, 다음의 코드를 참조하십시오

import org.apache.commons.codec.binary.Hex;
...
Hex.encodeHexString(someByteArray));

옵션 5 : 구글 구아바

일반적으로, 당신은 구아바 의존성 등을. 이 경우 사용하십시오 :

import com.google.common.io.BaseEncoding;
...
BaseEncoding.base16().lowerCase().encode(someByteArray);

옵션 6 : 봄 보안

는 IF 스프링 프레임 워크스프링 보안이 사용하려면 다음을 사용할 수 있습니다 :

import org.springframework.security.crypto.codec.Hex
...
new String(Hex.encode(someByteArray));

옵션 7 : 풍선 성

이미 보안 프레임 워크를 사용하는 경우 탄력이 성을 , 당신은 사용할 수 있습니다 HexUTIL를 :

import org.bouncycastle.util.encoders.Hex;
...
Hex.toHexString(someByteArray);

별로 옵션 8 : 자바 9+ 호환성 또는 "사용하지 않는 JAXB 모두 javax / XML / 바인드 / DatatypeConverter"

(아래 8) 이전 자바 버전은 JAXB 자바 코드 종속성은 실행으로 포함되어 있습니다. 자바 9 있기 때문에 직소 모듈 명시 적 진술이없는 경우, 코드는 모듈의 다른 코드 외부에 액세스 할 수 없습니다. 따라서, 다음과 같은 예외 여부에 관심을 지불하시기 바랍니다 :

java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

JVM을에서 실행 자바 9+ 시간이. 그렇다면, 그것은 위의 모든 달성한다 선택 스위치. 이 참조 문제를 .


소형 벤치 마크

이것은 간단 JMH의 인코딩 마이크로 기준, 다른 사이즈의 바이트 배열의 결과 . 이 값은 너무 초당 작업 수있는 더 높은. 마이크로 벤치 마크는 일반적으로 실제 동작을 나타내지 않는 것을 참고, 그래서 그냥 소금을 기쁘게하십시오.

| Name (ops/s)         |    16 byte |    32 byte |  128 byte | 0.95 MB |
|----------------------|-----------:|-----------:|----------:|--------:|
| Opt1: BigInteger     |  2,088,514 |  1,008,357 |   133,665 |       4 |
| Opt2/3: Bytes Lib    | 20,423,170 | 16,049,841 | 6,685,522 |     825 |
| Opt4: Apache Commons | 17,503,857 | 12,382,018 | 4,319,898 |     529 |
| Opt5: Guava          | 10,177,925 |  6,937,833 | 2,094,658 |     257 |
| Opt6: Spring         | 18,704,986 | 13,643,374 | 4,904,805 |     601 |
| Opt7: BC             |  7,5016,66 |  3,674,422 | 1,077,236 |     152 |
| Opt8: JAX-B          | 13,497,736 |  8,312,834 | 2,590,940 |     346 |

사양 : JDK 8u202, i7-7700K, Win10,24GB 램 . 제발 여기에 전체 벤치 마크를 볼 수 있습니다.


하우스 # 24

저는 여기에 세 가지 방법을 발견 : HTTP : //www.rgagnon.com/javadetails/java-0596.html

그가 지적한 바와 같이, 그것은 가장 우아한 중 하나입니다 :

static final String HEXES = "0123456789ABCDEF";
public static String getHex( byte [] raw ) {
    if ( raw == null ) {
        return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
            .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

하우스 # 25

아파치 코 몬즈 코덱 라이브러리는이 육각 등의 작업을 수행하는 데 사용되는 클래스를.

import org.apache.commons.codec.binary.Hex;

String foo = "I am a string";
byte[] bytes = foo.getBytes();
System.out.println( Hex.encodeHexString( bytes ) );

하우스 # 26

으로 특히 토론, 나는 현재 기능을 사용 대답 :

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    }
    return new String(hexChars);
}

나는 그것이 훨씬 더 빨리 배열의 절반 길이에 관한 다른 어떤 방법보다 것이라는 작은 벤치 마크 (킬로바이트 천 바이트, 256 바이트 기가 바이트)를 소유하고 있습니다. 토론에 제안 - - 나는 비트 단위로 전환 얻을 응답에 비해 긴 시간의 배열이 약 20 % 감소. (편집자는 : 나는 다른 방법보다 더 빨리 말할 때, 토론에 제공되는 사용되는 코드와 매우 유사하다 커먼즈 코덱에 다른 코드와 동등한 성능을 의미합니다.)

원저는 0 출판 · 원의 칭찬 0 · 조회수 2245을

추천

출처blog.csdn.net/p15097962069/article/details/103874576