Java tutorial
//package com.java2s; public class Main { /** * new byte[]{13, 0} => 00001101, 00000000 => 8 = 1, 10 = 1, 11 = 1 * * @param src * @param index * @return */ public static byte getBitData(byte[] src, int index) { return getBitData(src, index, true); } public static byte getBitData(byte[] src, int index, boolean isLH) { return getBitData(src, index, index + 1, isLH)[0]; } /** * new byte[]{13, 0} => 00001101, 00000000 => 8-11 = new byte[]{1, 0, 1, 1} * * @param src * @param index * @return */ public static byte[] getBitData(byte[] src, int start, int end) { return getBitData(src, start, end, true); } public static byte[] getBitData(byte[] src, int start, int end, boolean isLH) { byte[] result = null; StringBuffer sb = new StringBuffer(); for (byte b : src) { sb.append(getBinaryString(b)); } String bitString = (isLH ? sb : sb.reverse()).substring(start, end); result = new byte[bitString.length()]; for (int i = 0; i < bitString.length(); i++) { result[i] = Byte.valueOf(String.valueOf(bitString.charAt(i))); } return result; } /** * 7 => 00000111 * * @param src * @return */ public static String getBinaryString(byte src) { String binaryString = Integer.toBinaryString(src); if (binaryString.length() > Byte.SIZE) { binaryString = binaryString.substring(binaryString.length() - Byte.SIZE); } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < Byte.SIZE - binaryString.length(); i++) { sb.append("0"); } binaryString = sb.toString() + binaryString; } return binaryString; } }