集册 Java实例教程 在位集和字节数组之间转换

在位集和字节数组之间转换

欢马劈雪     最近更新时间:2020-01-02 10:19:05

551
在位集和字节数组之间转换

import java.util.BitSet;


public class Main {

  public static BitSet fromByteArray(byte[] bytes) {/** 来自 N o  w  J a v a . c o m - 时  代  Java**/

    BitSet bits = new BitSet();

    for (int i = 0; i < bytes.length * 8; i++) {

      if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {

        bits.set(i);

      }

    }

    return bits;

  }


  public static byte[] toByteArray(BitSet bits) {

    byte[] bytes = new byte[bits.length() / 8 + 1];

    for (int i = 0; i < bits.length(); i++) {

      if (bits.get(i)) {
  
展开阅读全文