I have the following:
int num=Integer.parseInt(lineArray[0]);
byte numBit= num & 0xFF;
Is there any very simple way to convert numBit
to a bit array? Or even better, is there a way to bypass the byte conversion of the int and go straigh from num
to a bit array?
Thanks
Java Integer byteValue() MethodThe byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.
When you want to convert an int value to a byte array, you can use the static method ByteArray. toByteArray(). This method takes an int input and returns a byte array representation of the number.
Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .
Java 7 has BitSet.valueOf(long[]) and BitSet.toLongArray()
int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
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
};
}
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