简体   繁体   中英

Java generic convert byte array to string (Non hex, decimal)

What is the best way to convert a byte array to a string with a radix of choice? There is a ton of examples here on SO and elsewhere to convert to a hex string. What I am mainly interested in here is converting to something other than a hex or decimal string; also a more generic way.

This is what I currently do:

byte[] input;
String MyStr = new BigInteger(input).toString(radix);

This works, but since Java has a concept of radix, as used in the Integer . This seems to be the explicit purpose as defined in Character . Shouldn't there be a better way of doing this rather than to first convert the byte array to a BigInteger? It feels like my Java knowledge misses some essential standard class?

EDIT: I would like to use this for a compressed way of representing (and printing) raw binary data of different types. This is the actual radix I currently use:

String MyStr = new BigInteger(data).toString(Character.MAX_RADIX);

The MAX_RADIX (36) uses a combination of lower case letters and numbers. This gives a decent compression, but would be even better if the radix could include UPPER letters, which is why I thought I may be missing something.

It seems like you're looking for Base64 encoding. This uses 64 different characters to encode a value: upper case and lower case letters (that's 52 characters already), digits (10 more, including the '0'), and the '+' and '/' symbols (or '-' and '_' in the url-safe variation).

If you're using Java 8, there's the Base64 class:

String str = Base64.Encoder.encodeToString(data);

Otherwise, Apache Commons has a Base64 class too:

String str = Base64.encodeBase64String(data);

That's a good one, actually, I'm not sure neither if there's a class to achieve that. But another way to do what you want without using BigInteger is to iterate over the array and get the output, something like:

for(byte b : input){
    System.out.print(Integer.toString(b & 0xFF, radix));
}

Not sure about an specific class doing a conversion, but this is another approach I know, maybe could be useful to you or to somebody else.

Happy coding.

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM