Java tutorial
//package com.java2s; /************************************************************************ * 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) * ************************************************************************/ public class Main { static private final String lookupTable = "01"; /** * This function decodes a base 2 string into its corresponding byte array. * * @param base2 The base 2 encoded string. * @return The corresponding byte array. */ static public byte[] decode(String base2) { String string = base2.replaceAll("\\s", ""); // remove all white space int length = string.length(); byte[] bytes = new byte[(int) Math.ceil(length / 8)]; for (int i = 0; i < bytes.length; i++) { int b = 0; for (int j = 0; j < 8; j++) { char character = string.charAt(i * 8 + j); int bit = lookupTable.indexOf(character); if (bit < 0) throw new NumberFormatException("Attempted to decode a string that is not base 2: " + string); b = (b << 1) | bit; } bytes[i] = (byte) b; } return bytes; } }