开发者

Is there a simpler way to convert a byte array to a 2-byte-size hexadecimal string?

开发者 https://www.devze.com 2022-12-27 04:46 出处:网络
Is there a simpler way of implement this? Or a implemented method in JDK or other lib? /** * Convert a byte array to 2-byte-size hexadecimal String.

Is there a simpler way of implement this? Or a implemented method in JDK or other lib?

/**
 * Convert a byte array to 2-byte-size hexadecimal String.
 */
public static String to2DigitsHex(byte[] bytes) {
String hexData = "";
for (int i = 0; i < bytes开发者_如何学Python.length; i++) {
    int intV = bytes[i] & 0xFF; // positive int
    String hexV = Integer.toHexString(intV);
    if (hexV.length() < 2) {
    hexV = "0" + hexV;
    }
    hexData += hexV;
}
return hexData;
}

public static void main(String[] args) {
System.out.println(to2DigitsHex(new byte[] {8, 10, 12}));
}

the output is: "08 0A 0C" (without the spaces)


Use at least StringBuilder#append() instead of stringA += stringB to improve performance and save memory.

public static String binaryToHexString(byte[] bytes) {
    StringBuilder hex = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
        int i = (b & 0xFF);
        if (i < 0x10) hex.append('0');
        hex.append(Integer.toHexString(i));
    }
    return hex.toString();
}


Apache Commons-Codec has the Hex class, which will do what you need:

String hexString = Hex.encodeHexString(bytes);

By far the easiest method. Don't mess with binary operators, use the libraries to do the dirty work =)


public static String to2DigitsHex(final byte[] bytes) {
    final StringBuilder accum = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
      b &= 0xff;
      if (b < 16) accum.append("0");
      accum.append(Integer.toHexString(b);
    }
    return accum.toString();
}

You're better off using an explicit StringBuilder of your own if this routine is going to be called a lot.


 private static String to2DigitsHex(byte[] bs) {
      String s = new BigInteger(bs).toString(16);
      return s.length()%2==0? s : "0"+s;
 }


You could use BigInteger for this.

Example:

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

You will need to add an '0' at the beginning.

A more elegant solution (taken from here) is:

BigInteger i = new BigInteger(1,bytes);
System.out.println(String.format("%1$06X", i));

You need to know the number of bytes in advance in order to use the correct formatter.


I'm not taking any credit for this implementation as I saw it as part of a similar discussion and thought it was an elegant solution:

private static final String HEXES = "0123456789ABCDEF";

public String toHexString(byte[] bytes) {
    final StringBuilder hex = new StringBuilder(2 * bytes.length);
    for (final byte b : _bytes) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
           .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消