Over a million developers have joined DZone.

Simple Toolkit For Translation Between Byte Array And Hex String

·
// description of your code here


package flib.util;

import java.util.Locale;

/**
 * BD : Simple Kit for translation between byte array and hex string.
 * @author John-Lee
 */
public class HexByteKit {
    private static byte charToByte(char c){
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * BD : Used to transfer hex string into byte array. two hex string combines one byte. So that means the length of hex string
     *      should be even. Or the null will be returned.
     * @param hexStr
     * @return
     */
    public static byte[] hex2byte(String hexStr) {
        if(hexStr == null || hexStr.isEmpty() || (hexStr.length()%2>1)) {
            return null;
        }
        String hexStrUp = hexStr.toUpperCase();
        int length = hexStrUp.length()/2;
        char[] hexChars = hexStrUp.toCharArray();
        byte[] resultByte = new byte[length];
        for(int i=0;i
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}