byte的二進制
public static boolean[] byte2BitArray(byte value){
boolean[] booleans = new boolean[Byte.SIZE];
for(int j=0;j<Byte.SIZE;j++){
booleans[j]=((value >> (Byte.SIZE-j-1)) & 0x1)==1?true:false;
}
return booleans;
}
二進制轉Byte
public static byte bitArray2Byte(boolean[] value,int start){
byte result = 0x00;
if(start<value.length&&start+Byte.SIZE<value.length){
int i=start;
while(i-start<Byte.SIZE){
if(value[i]){
result|=(1<<(Byte.SIZE+start-i-1))&0xff;
}
i++;
}
return result;
}else{
throw new IndexOutOfBoundsException();
}
}
二進制轉字節數組
public static byte[] bitArray2Bytes(boolean[] value,int start,int len){
byte[] result=null;
if((start+len)*Byte.SIZE<=value.length){
result=new byte[len];
for(int i=start;i<len;i++){
for(int j=0;j<Byte.SIZE;j++){
if(value[(i+1)*Byte.SIZE-j-1]){
result[i]|=(1<<j)&0xff;
}
}
}
}
return result;
}
字節數組的二進制
public static boolean[] bytes2BitArray(byte[] value){
boolean[] booleans = new boolean[value.length*Byte.SIZE];
for(int i=0;i<value.length;i++){
for(int j=0;j<Byte.SIZE;j++){
booleans[(i+1)*Byte.SIZE-j-1]=(value[i]>>j& 0x1)==1;
}
}
return booleans;
}
字符串與二進制流相互轉換
public static boolean[] str2BitArray(String value){
boolean[] booleans = new boolean[value.length()*Byte.SIZE];
byte[] src = value.getBytes();
for(int i=0;i<src.length;i++){
for(int j=0;j<Byte.SIZE;j++){
booleans[(i+1)*Byte.SIZE-j-1]=((src[i] >> j) & 0x1)==1?true:false;
}
}
return booleans;
}
public static String bitArray2Str(boolean[] booleans){
StringBuilder sb=new StringBuilder();
for(int i=0;i<booleans.length;i+=Byte.SIZE){
int result=0;
for(int j=0;j<Byte.SIZE;j++){
result+=(booleans[i+Byte.SIZE-j-1]?1:0)<<j;
}
sb.append((char)result);
}
return sb.toString();
}
int與Byte相互轉換
public static byte[] int2Bytes(int value){
byte[] src = new byte[Integer.BYTES];
for(int i=0;i<Integer.BYTES;i++){
src[i]=(byte) ((value>>(8*(Integer.BYTES-i-1))) & 0xFF);
}
return src;
}
public static int bytes2Int(byte[] value){
int result=0;
for(int i=0;i<Integer.BYTES;i++){
result<<=8;
result|=(value[i]&0xFF);
}
return result;
}
long與byte互轉
public static byte[] long2Bytes(long num) {
byte[] byteNum = new byte[Long.BYTES];
for (int i = 0; i < 8; ++i) {
byteNum[i] = (byte) ((num >> (Long.BYTES-i-1)*Byte.SIZE) & 0xff);
}
return byteNum;
}
public static long bytes2Long(byte[] byteNum) {
long num = 0;
for (int i = 0; i < Long.BYTES; ++i) {
num <<= 8;
num |= (byteNum[i] & 0xff);
}
return num;
}