首页 > 代码库 > boolean与byte的互转

boolean与byte的互转

public static byte[] toBytes(boolean[] arrs){        int f = 0;byte b = 0;        byte[] ret = new byte[arrs.length/7 + (arrs.length%7==0?0:1)];        for(int i=0; i<arrs.length; i+=8){            for(int j=0; j<8; j++){                if(i+j<arrs.length && arrs[i+j]){                    b+= (1<<(7-j));                }                if(j==7){                    ret[f++] = b;                    b = 0;                }            }        }        return ret;    }        public static boolean[] toBoolean(byte[] bs, int length){        boolean[] arrs = new boolean[8*bs.length];        for(int i=0; i<bs.length; i++){            int indx = i*8;            byte b = bs[i];            for(int j=7; j>=0; j--){                arrs[indx + j] = (b&1)==1;                b = (byte)(b>>1);            }        }        return Arrays.copyOfRange(arrs, 0, length);    }