软件编程
位置:首页>> 软件编程>> java编程>> 浅谈byte和长度为8的boolean数组互相转换

浅谈byte和长度为8的boolean数组互相转换

作者:jingxian  发布时间:2023-11-07 00:34:37 

标签:java,byte,boolean

由于byte是一个8位字节

所以可以用它来存放数组为8的boolean数组,这些在通信协议会经常用到。这里给出一个java代码对其互相转换的。


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));

}
/**
  * 将byte转换为一个长度为8的boolean数组(每bit代表一个boolean值)
  *
  * @param b byte
  * @return boolean数组
  */
 public static boolean[] getBooleanArray(byte b) {
   boolean[] array = new boolean[8];
   for (int i = 7; i >= 0; i--) { //对于byte的每bit进行判定
     array[i] = (b & 1) == 1;  //判定byte的最后一位是否为1,若为1,则是true;否则是false
     b = (byte) (b >> 1);    //将byte右移一位
   }
   return array;
 }

/**
  * 将一个长度为8的boolean数组(每bit代表一个boolean值)转换为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;
 }

}
0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com