Here you can find the source of bitsToHexString(BitSet ba, int size)
public static String bitsToHexString(BitSet ba, int size)
//package com.java2s; /*/*www . j a v a2s .c o m*/ * This file is part of dhcp4java, a DHCP API for the Java language. * (c) 2006 Stephan Hadinger * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ import java.util.BitSet; public class Main { /** * Pack the bits in ba into a byte[] then convert that * to a hex string and return it. */ public static String bitsToHexString(BitSet ba, int size) { return bytesToHex(bitsToBytes(ba, size)); } /** * Converts a byte array into a string of upper case hex chars. * * <at> param bs * A byte array * <at> param off * The index of the first byte to read * <at> param length * The number of bytes to read. * <at> return the string of hex chars. */ public static String bytesToHex(byte[] bs, int off, int length) { StringBuffer sb = new StringBuffer(length * 2); bytesToHexAppend(bs, off, length, sb); return sb.toString(); } public static String bytesToHex(byte[] bs) { return bytesToHex(bs, 0, bs.length); } /** * Pack the bits in ba into a byte[]. */ public static byte[] bitsToBytes(BitSet ba, int size) { int bytesAlloc = countBytesForBits(size); byte[] b = new byte[bytesAlloc]; for (int i = 0; i < b.length; i++) { short s = 0; for (int j = 0; j < 8; j++) { int idx = i * 8 + j; boolean val = (idx <= size && ba.get(idx)); s |= (val ? (1 << j) : 0); } if (s > 255) { throw new IllegalStateException("WTF? s = " + s); } b[i] = (byte) s; } return b; } public static void bytesToHexAppend(byte[] bs, int off, int length, StringBuffer sb) { sb.ensureCapacity(sb.length() + length * 2); for (int i = off; i < (off + length) && i < bs.length; i++) { sb.append(Character.forDigit((bs[i] >>> 4) & 0xf, 16)).append(Character.forDigit(bs[i] & 0xf, 16)); } } /** * <at> return the number of bytes required to represent the * bitset */ public static int countBytesForBits(int size) { // Brackets matter here! == takes precedence over the rest return (size / 8) + ((size % 8) == 0 ? 0 : 1); } }