On the conversion of a Boolean array of byte and length 8 to one another _java

Source: Internet
Author: User
Tags arrays

Because Byte is a 8-bit byte

So you can use it to hold a Boolean array of 8, which is often used in communication protocols. This gives a Java code to convert it 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 met
		
		 Hod 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)); /** * Converts byte to a Boolean array of length 8 (each bit represents a Boolean value) * * @param b Byte * @return Boolean array/public STA
    Tic boolean[] Getbooleanarray (byte b) {boolean[] array = new BOOLEAN[8];  for (int i = 7; I >= 0; i--) {//For each bit of byte to determine array[i] = (b & 1) = 1;    Determines whether the last digit of byte is 1 and, if 1, is true, otherwise it is false B = (byte) (b >> 1);
  Move byte Right one} return array;
/** * Converts a Boolean array of length 8 (each bit representing a Boolean value) to a 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; }
  
}

The above article on the byte and length of 8 Boolean array conversion is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.