當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BitSet toByteArray()用法及代碼示例


java.util.BitSet.toByteArray()是BitSet類的內置方法,用於生成包含現有BitSet的所有位的新字節數組。根據官方文檔,此過程以以下方式工作:

if, byte[] bytes = bit_set.toByteArray();
then, bytes.length == (bit_set.length()+7)/8 and,
bit_set.get(n) == ((bytes[n/8] & (1

For all n

用法:

Bit_Set.toByteArray()

參數:該方法不帶任何參數。

返回值:該方法返回由給定BitSet的元素的ByteArray表示形式組成的集合。

以下程序說明了java.util.BitSet.toByteArray()方法的用法:
示例1:

// Java code to illustrate toByteArray() 
import java.util.*; 
  
public class BitSet_Demo { 
    public static void main(String args[]) 
    { 
        // Creating an empty BitSet 
        BitSet init_bitset = new BitSet(); 
  
        // Use set() method to add elements into the Set 
        init_bitset.set(10); 
        init_bitset.set(20); 
        init_bitset.set(30); 
        init_bitset.set(40); 
        init_bitset.set(50); 
  
        // Displaying the BitSet 
        System.out.println("BitSet: " + init_bitset); 
  
        byte[] arr = init_bitset.toByteArray(); 
        System.out.println("The byteArray is: " + arr); 
  
        // Displaying the byteArray 
        System.out.println("The elements in the byteArray :"); 
        for (int i = 0; i < arr.length; i++) 
            System.out.print(arr[i] + ", "); 
    } 
}
輸出:
BitSet: {10, 20, 30, 40, 50}
The byteArray is: [B@232204a1
The elements in the byteArray :
0, 4, 16, 64, 0, 1, 4,

示例2:

// Java code to illustrate toByteArray() 
import java.util.*; 
  
public class BitSet_Demo { 
    public static void main(String args[]) 
    { 
        // Creating an empty BitSet 
        BitSet init_bitset = new BitSet(); 
  
        // Use set() method to add elements into the Set 
        init_bitset.set(48); 
        init_bitset.set(64); 
        init_bitset.set(15); 
        init_bitset.set(95); 
        init_bitset.set(105); 
        init_bitset.set(21); 
  
        // Displaying the BitSet 
        System.out.println("BitSet: " + init_bitset); 
  
        byte[] arr = init_bitset.toByteArray(); 
        System.out.println("The byteArray is: " + arr); 
  
        // Displaying the byteArray 
        System.out.println("The elements in the byteArray :"); 
        for (int i = 0; i < arr.length; i++) 
            System.out.print(arr[i] + ", "); 
    } 
}
輸出:
BitSet: {15, 21, 48, 64, 95, 105}
The byteArray is: [B@232204a1
The elements in the byteArray :
0, -128, 32, 0, 0, 0, 1, 0, 1, 0, 0, -128, 0, 2,


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 BitSet toByteArray() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。