Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a byte or int to bitset

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

like image 424
moesef Avatar asked Aug 05 '12 21:08

moesef


People also ask

How do you convert int to byte value?

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.

How do you convert int to ByteArray?

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.

How to convert bytes[] to String Java?

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) .


2 Answers

Java 7 has BitSet.valueOf(long[]) and BitSet.toLongArray()

int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
like image 116
Grigory Kislin Avatar answered Sep 21 '22 07:09

Grigory Kislin


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
  };
}
like image 43
obataku Avatar answered Sep 23 '22 07:09

obataku