This function decodes a base 16 string into its corresponding byte array. - Java java.lang

Java examples for java.lang:String Base64

Description

This function decodes a base 16 string into its corresponding byte array.

Demo Code

/************************************************************************
 * Copyright (c) Crater Dog Technologies(TM).  All Rights Reserved.     *
 ************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.        *
 *                                                                      *
 * This code is free software; you can redistribute it and/or modify it *
 * under the terms of The MIT License (MIT), as published by the Open   *
 * Source Initiative. (See http://opensource.org/licenses/MIT)          *
 ************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String base16 = "java2s.com";
        System.out.println(java.util.Arrays.toString(decode(base16)));
    }/* w w  w .  jav a 2 s . c o  m*/

    static private final String lookupTable = "0123456789ABCDEF";

    /**
     * This function decodes a base 16 string into its corresponding byte array.
     *
     * @param base16 The base 16 encoded string.
     * @return The corresponding byte array.
     */
    static public byte[] decode(String base16) {
        String string = base16.replaceAll("\\s", ""); // remove all white space
        int length = string.length();
        byte[] bytes = new byte[(int) Math.ceil(length / 2)];
        for (int i = 0; i < bytes.length; i++) {
            char firstCharacter = string.charAt(i * 2);
            int firstNibble = lookupTable.indexOf((int) firstCharacter);
            if (firstNibble < 0)
                throw new NumberFormatException(
                        "Attempted to decode a string that is not base 16: "
                                + string);
            char secondCharacter = string.charAt(i * 2 + 1);
            int secondNibble = lookupTable.indexOf((int) secondCharacter);
            if (secondNibble < 0)
                throw new NumberFormatException(
                        "Attempted to decode a string that is not base 16: "
                                + string);
            bytes[i] = (byte) ((firstNibble << 4) | secondNibble);
        }
        return bytes;
    }
}

Related Tutorials