Convert byte[] to BitSet
One cannot compare two byte[]
arrays directly, as byte[]
s dont implement comparable. The solution here would be to wrap them in a ByteBuffer, as suggested by @PaulBoddington.
assertEquals(ByteBuffer.wrap(expectedOutput.toByteArray()),ByteBuffer.wrap(input));
The other length issue is caused by BitSet
itself. BitSet.length()
returns the length from index 0 to the last set bit in the BitSet
, which would cause the discrepancy in the length of the BitSet.length()
vs the byte[].length*8
. The only solution here would be to use BitSet.toByteArray().length*8
, where ever there is a need for BitSet.length()
.
Convert Byte Array into Bitset
Something like this?
#include <bitset>
#include <climits>
template<size_t numBytes>
std::bitset<numBytes * CHAR_BIT> bytesToBitset(uint8_t *data)
{
std::bitset<numBytes * CHAR_BIT> b;
for(int i = 0; i < numBytes; ++i)
{
uint8_t cur = data[i];
int offset = i * CHAR_BIT;
for(int bit = 0; bit < CHAR_BIT; ++bit)
{
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
return b;
}
And an example usage:
int main()
{
std::array<uint8_t, 4> bytes = { 0xDE, 0xAD, 0xBE, 0xEF };
auto bits = bytesToBitset<bytes.size()>(bytes.data());
std::cout << bits << std::endl;
}
Convert a byte or int to bitset
If you want a BitSet, try:
final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });
If you want a boolean[]
,
static boolean[] bits(byte b) {
int n = 8;
final boolean[] set = new boolean[n];
while (--n >= 0) {
set[n] = (b & 0x80) != 0;
b <<= 1;
}
return set;
}
or, equivalently,
static boolean[] bits(final byte b) {
return new boolean[] {
(b & 1) != 0,
(b & 2) != 0,
(b & 4) != 0,
(b & 8) != 0,
(b & 0x10) != 0,
(b & 0x20) != 0,
(b & 0x40) != 0,
(b & 0x80) != 0
};
}
How to write into BitSet from byteArray? (we need java 1.7)
If you refer docs of BitSet , there is valueOf()
method
public static BitSet valueOf(byte[] bytes)
Returns a new bit set containing all the bits in the given byte array.
BitSet a = BitSet.valueOf(test);
Byte to Bitarray
Because there is no bit data type that exists on the physical computer. The smallest allotment you can allocate on most modern computers is a byte which is also known as an octet or 8 bits. When you display a single bit you are really just pulling that first bit out of the byte with arithmetic and adding it to a new byte which still is using an 8 bit space. If you want to put bit data inside of a byte you can but it will be stored as a at least a single byte no matter what programming language you use.
Why is wrong bit representation got by converting byte array to BitSet in Java
It appears that you are printing the bits backwards. Notice how your output (except for the desired leading zeros) is a mirror image of your expected input.
Using your code, passing in 4
, which should be 100
, I get 001
. It appears that bit 0
is the least significant bit, not the most significant bit. To correct this, loop over the indices backwards. The reason that -1
and 41
are correct apart from the leading zeros is that their bitset representations are palindromes.
To prepend leading zeros, subtract the length()
from 8
and print that many zeros. The length()
method only returns the number of bits necessary to represent the number. You need to code this yourself; there is no BitSet
functionality for leading zeros.
How do I convert a bitSet initialized with false in a byte containing 0 in java
From the Javadoc of toByteArray()
:
More precisely, if
byte[] bytes = s.toByteArray();
then
bytes.length == (s.length()+7)/8
and from the Javadoc of length()
:
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.
Since the second BitSet
contains no set bits, it returns an array of length zero, as the Javadoc clearly specifies.
If you want to pad the result of toByteArray()
out to a specified number of bytes, then use Arrays.copyOf(bitSet.toByteArray(), desiredLength)
.
Related Topics
How to Efficiently Wait for Cts or Dsr of Rs232 in Linux
a Few Things About Division by Zero in C
Passing a Non-Copyable Closure Object to Std::Function Parameter
How to Convert a Tchar Array to Std::String
How Get Uuid of a Device/Partition in Linux Programatically
Segmentation Fault Before Main() When Using Glut, and Std::String
Get Device Path Based on Usb Vid:Pid in Linux
Running a Windows Program and Detect When It Ends with C++
C++: What Is the Printf() Format Spec for "Float"
Why Ld_Preload Doesn't Work for One of Loaded Shared Libraries
How to Get Vendor Id and Product Id of a Plugged Usb Device on Windows
What Is a C++11 Extension [-Wc++11-Extensions]
Constructor as a Function Try Block - Exception Aborts Program
Finding C++ Interval Tree Algorithm Implementation
Dealing with Library Dependencies on Linux
C++11 Member Initialization List Ambiguity
How to Find The Full Path of The C++ Linux Program from Within