How would I go about converting a bytearray to a bit array?
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.
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.
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..
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.
The obvious way; using the constructor that takes a byte array:
BitArray bits = new BitArray(arrayOfBytes);
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With