Talk about converting byte and boolean arrays of length 8 to each other

  • 2020-05-17 05:32:58
  • OfStack

Because byte is an 8-bit byte

So you can use it to store the boolean array of array 8, which is often used in communications protocols. Here is an java code that converts them to each other.


package com.udpdemo.test2;

import java.util.Arrays;

public class Test {

	/**
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Byte.SIZE);
		
		 byte b = 0x35; // 0011 0101
		 System.out.println(b);
		 System.out.println(Arrays.toString(getBooleanArray(b)));
		 
		 //0x35; // 0011 0101
		 boolean[] array = new boolean[]{false, false, true, true, false, true, false, true};
	 
		 System.out.println(getByte(array));
		 
		
		
	}
	 /**
   *  will byte convert 1 A length of 8 the boolean Array (every bit On behalf of 1 a boolean Value) 
   * 
   * @param b byte
   * @return boolean An array of 
   */
  public static boolean[] getBooleanArray(byte b) {
    boolean[] array = new boolean[8];
    for (int i = 7; i >= 0; i--) { // for byte Each of the bit To determine 
      array[i] = (b & 1) == 1;  // determine byte At the end of the 1 Whether a is 1 If, for 1 , it is true ; It is false
      b = (byte) (b >> 1);    // will byte Moves to the right 1 position 
    }
    return array;
  }

  /**
   *  will 1 A length of 8 the boolean Array (every bit On behalf of 1 a boolean Value) to byte
   * @param array
   * @return
   *
   */
  public static byte getByte(boolean[] array) {
  	if(array != null && array.length > 0) {
  		byte b = 0;
  		for(int i=0;i<=7;i++) {
  			if(array[i]){
  				int nn=(1<<(7-i));
  				b += nn;
  			}
  		}
  		return b;
  	}
  	return 0;
  }
  
}

Related articles: