如何将一个字节数组转换成Java中的十六进制字符串?

时间:2022-10-30 15:49:54

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in the form of: 3a5f771c

我有一个填充了十六进制数字的字节数组,并且打印它很简单,因为有许多不可打印的元素。我需要的是精确的hexcode: 3a5f771c !

20 个解决方案

#1


704  

From the discussion here, and especially this answer, this is the function I currently use:

从这里的讨论,特别是这个答案,这是我目前使用的函数:

private final static char[] hexArray = "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] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

我自己的小型基准测试(一百万字节一千次,256字节1000万次)显示它比其他任何方法都快得多,大约是长数组的一半。与我的回答相比,切换到bitwise项目——就像讨论中建议的那样——在长时间的数组中减少大约20%的时间。(编辑:当我说它比其他选项快的时候,我指的是讨论中提供的替代代码。性能相当于Commons Codec,它使用非常类似的代码。

#2


317  

The Apache Commons Codec library has a Hex class for doing just this type of work.

Apache Commons Codec库有一个Hex类来完成这类工作。

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

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

#3


283  

Use DatatypeConverter.printHexBinary(). You can read its documentation in http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html

使用DatatypeConverter.printHexBinary()。您可以在http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html中阅读它的文档。

For example:

例如:

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

Will result in:

将导致:

000086003D

As you can see this will retrieve the hexadecimal string representing the array of bytes with leading zeros.

正如您所看到的,它将检索表示字节数组的十六进制字符串。

This answer is basically the same as in the question In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

这个答案基本上与Java中的问题相同,我如何将一个字节数组转换成一个十六进制数字串,同时保持前导零?

#4


175  

Simplest solution, no external libs, no digits constants:

最简单的解,没有外部libs,没有数字常数:

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();
}

#5


36  

This simple oneliner works for me
String result = new BigInteger(1, inputBytes).toString(16);
EDIT - Using this will remove the leading zeros, but hey worked for my use-case. Thanks @Voicu for pointing it out

这个简单的oneliner为我工作,String result = new BigInteger(1, inputBytes).toString(16);编辑-使用这将删除前导零,但是嘿为我的用例工作。感谢@Voicu指出来。

#6


35  

A Guava solution, for completeness:

一个番石榴溶液,为了完整性:

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

Now hex is "48656c6c6f20776f726c64".

现在十六进制是“48656 c6c6f20776f726c64”。

#7


17  

Use DataTypeConverter classjavax.xml.bind.DataTypeConverter

使用DataTypeConverter classjavax.xml.bind.DataTypeConverter

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

字符串hexString = DatatypeConverter。printHexBinary(原始字节[]);

#8


12  

I found three different ways here: http://www.rgagnon.com/javadetails/java-0596.html

我在这里找到了三种不同的方法:http://www.rgagnon.com/javadetails/java0596.html。

The most elegant one, as he also notes, I think is this one:

最优雅的一个,他也提到过,我认为是这个:

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();
}

#9


12  

At the minor cost of storing the lookup table this implementation is simple and very fast.

在存储查找表的次要成本中,这个实现非常简单而且非常快。

 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);
  }

#10


7  

How about this?

这个怎么样?

    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;
    }

#11


6  

I would use something like this for fixed length, like hashes:

我会用像这样的固定长度,比如哈希:

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

#12


2  

I prefer to use this:

我更喜欢用这个:

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);
}

It is slightly more flexible adaptation of the accepted answer. Personally, I keep both the accepted answer and this overload along with it, usable in more contexts.

这是根据公认的答案稍微灵活一点。就我个人而言,我既保留了已接受的答案,也保留了这个重载,并在更多的上下文中使用。

#13


2  

I usually use the following method for debuf statement, but i don't know if it is the best way of doing it or not

我通常使用下面的方法来进行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();
}

#14


2  

Ok so there are a bunch of ways to do this, but if you decide to use a library I would suggest poking about in your project to see if something has been implemented in a library that is already part of your project before adding a new library just to do this. For example if you don't already have

所以有很多方法可以做到这一点,但是如果你决定使用一个图书馆我建议戳在您的项目是否有在库,已经部分实现之前您的项目添加一个新图书馆。例如,如果你还没有。

org.apache.commons.codec.binary.Hex

org.apache.commons.codec.binary.Hex

maybe you do have...

也许你有…

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

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

#15


1  

A small variant of the solution proposed by @maybewecouldstealavan, which lets you visually bundle N bytes together in the output hex string:

@maybewecouldstealavan提出的解决方案的一个小变体,它允许您将N个字节可视化地打包在输出hex字符串中:

 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();    
}

That is:

那就是:

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

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

#16


0  

// Shifting bytes is more efficient // You can use this one too

//移动字节更有效率//你也可以使用这个。

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();
}

#17


0  

If you're looking for a byte array exactly like this for python, I have converted this Java implementation into python.

如果您正在寻找类似于python的字节数组,我已经将此Java实现转换为python。

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=[])

#18


0  

  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;
  } 

#19


0  

Here is a java.util.Base64-like implementation(partial), isn't it pretty?

这是一个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;
    }
    //...
}

#20


0  

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();
    }

#1


704  

From the discussion here, and especially this answer, this is the function I currently use:

从这里的讨论,特别是这个答案,这是我目前使用的函数:

private final static char[] hexArray = "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] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

我自己的小型基准测试(一百万字节一千次,256字节1000万次)显示它比其他任何方法都快得多,大约是长数组的一半。与我的回答相比,切换到bitwise项目——就像讨论中建议的那样——在长时间的数组中减少大约20%的时间。(编辑:当我说它比其他选项快的时候,我指的是讨论中提供的替代代码。性能相当于Commons Codec,它使用非常类似的代码。

#2


317  

The Apache Commons Codec library has a Hex class for doing just this type of work.

Apache Commons Codec库有一个Hex类来完成这类工作。

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

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

#3


283  

Use DatatypeConverter.printHexBinary(). You can read its documentation in http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html

使用DatatypeConverter.printHexBinary()。您可以在http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html中阅读它的文档。

For example:

例如:

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

Will result in:

将导致:

000086003D

As you can see this will retrieve the hexadecimal string representing the array of bytes with leading zeros.

正如您所看到的,它将检索表示字节数组的十六进制字符串。

This answer is basically the same as in the question In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

这个答案基本上与Java中的问题相同,我如何将一个字节数组转换成一个十六进制数字串,同时保持前导零?

#4


175  

Simplest solution, no external libs, no digits constants:

最简单的解,没有外部libs,没有数字常数:

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();
}

#5


36  

This simple oneliner works for me
String result = new BigInteger(1, inputBytes).toString(16);
EDIT - Using this will remove the leading zeros, but hey worked for my use-case. Thanks @Voicu for pointing it out

这个简单的oneliner为我工作,String result = new BigInteger(1, inputBytes).toString(16);编辑-使用这将删除前导零,但是嘿为我的用例工作。感谢@Voicu指出来。

#6


35  

A Guava solution, for completeness:

一个番石榴溶液,为了完整性:

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

Now hex is "48656c6c6f20776f726c64".

现在十六进制是“48656 c6c6f20776f726c64”。

#7


17  

Use DataTypeConverter classjavax.xml.bind.DataTypeConverter

使用DataTypeConverter classjavax.xml.bind.DataTypeConverter

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

字符串hexString = DatatypeConverter。printHexBinary(原始字节[]);

#8


12  

I found three different ways here: http://www.rgagnon.com/javadetails/java-0596.html

我在这里找到了三种不同的方法:http://www.rgagnon.com/javadetails/java0596.html。

The most elegant one, as he also notes, I think is this one:

最优雅的一个,他也提到过,我认为是这个:

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();
}

#9


12  

At the minor cost of storing the lookup table this implementation is simple and very fast.

在存储查找表的次要成本中,这个实现非常简单而且非常快。

 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);
  }

#10


7  

How about this?

这个怎么样?

    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;
    }

#11


6  

I would use something like this for fixed length, like hashes:

我会用像这样的固定长度,比如哈希:

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

#12


2  

I prefer to use this:

我更喜欢用这个:

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);
}

It is slightly more flexible adaptation of the accepted answer. Personally, I keep both the accepted answer and this overload along with it, usable in more contexts.

这是根据公认的答案稍微灵活一点。就我个人而言,我既保留了已接受的答案,也保留了这个重载,并在更多的上下文中使用。

#13


2  

I usually use the following method for debuf statement, but i don't know if it is the best way of doing it or not

我通常使用下面的方法来进行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();
}

#14


2  

Ok so there are a bunch of ways to do this, but if you decide to use a library I would suggest poking about in your project to see if something has been implemented in a library that is already part of your project before adding a new library just to do this. For example if you don't already have

所以有很多方法可以做到这一点,但是如果你决定使用一个图书馆我建议戳在您的项目是否有在库,已经部分实现之前您的项目添加一个新图书馆。例如,如果你还没有。

org.apache.commons.codec.binary.Hex

org.apache.commons.codec.binary.Hex

maybe you do have...

也许你有…

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

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

#15


1  

A small variant of the solution proposed by @maybewecouldstealavan, which lets you visually bundle N bytes together in the output hex string:

@maybewecouldstealavan提出的解决方案的一个小变体,它允许您将N个字节可视化地打包在输出hex字符串中:

 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();    
}

That is:

那就是:

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

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

#16


0  

// Shifting bytes is more efficient // You can use this one too

//移动字节更有效率//你也可以使用这个。

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();
}

#17


0  

If you're looking for a byte array exactly like this for python, I have converted this Java implementation into python.

如果您正在寻找类似于python的字节数组,我已经将此Java实现转换为python。

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=[])

#18


0  

  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;
  } 

#19


0  

Here is a java.util.Base64-like implementation(partial), isn't it pretty?

这是一个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;
    }
    //...
}

#20


0  

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();
    }