Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array to Bit Array?

How would I go about converting a bytearray to a bit array?

like image 224
cam Avatar asked Mar 30 '10 19:03

cam


People also ask

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

Can you convert byte into string?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

What is byte array in Java?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

What is BitArray in Python?

bitarray: efficient arrays of booleans. This library provides an object type which efficiently represents an array of booleans. Bitarrays are sequence types and behave very much like usual lists. Eight bits are represented by one byte in a contiguous block of memory.


2 Answers

The obvious way; using the constructor that takes a byte array:

BitArray bits = new BitArray(arrayOfBytes); 
like image 102
Guffa Avatar answered Sep 23 '22 09:09

Guffa


It depends on what you mean by "bit array"... If you mean an instance of the BitArray class, Guffa's answer should work fine.

If you actually want an array of bits, in the form of a bool[] for instance, you could do something like that :

byte[] bytes = ... bool[] bits = bytes.SelectMany(GetBits).ToArray();  ...  IEnumerable<bool> GetBits(byte b) {     for(int i = 0; i < 8; i++)     {         yield return (b & 0x80) != 0;         b *= 2;     } } 
like image 27
Thomas Levesque Avatar answered Sep 22 '22 09:09

Thomas Levesque