Answer with a bitmap equivalent to the hexadecimal string supplied - Java Language Basics

Java examples for Language Basics:Bit

Description

Answer with a bitmap equivalent to the hexadecimal string supplied

Demo Code


//package com.java2s;
import java.util.BitSet;

public class Main {
    public static void main(String[] argv) throws Exception {
        String hex = "java2s.com";
        System.out.println(hex2Bitset(hex));
    }//www.ja  v  a  2 s.  c o  m

    /**
     * Answer with a bitmap equivalent to the hexadecimal string supplied
     * @param hex string representation of an ISO8583 bitmap
     * @return a bitset initialized from the input hex string
     * @throws IllegalArgumentException if the hex string is null, empty or not even-sized
     */
    static BitSet hex2Bitset(final String hex) {
        final BitSet result = new BitSet();
        if (hex == null) {
            throw new IllegalArgumentException(
                    "Hex string must be non-null");
        }
        if (hex.length() == 0 || hex.length() % 2 != 0) {
            throw new IllegalArgumentException(
                    "Hex string must be even-sized (length=" + hex.length()
                            + ")");
        }
        final int length = hex.length();
        int bytenum = (length / 2) - 1;
        for (int index = length; index >= 2; index -= 2) {
            final int bytevalue = Integer.valueOf(
                    hex.substring(index - 2, index), 16);
            for (int bit = 0, mask = 0x80; mask >= 0x01; bit++, mask /= 2) {
                if ((mask & bytevalue) == mask) {
                    result.set((bytenum * 8) + bit);
                }
            }
            bytenum--;
        }
        return result;
    }
}

Related Tutorials