How to create 32 bit mask in Java - java

So far I have this code to create 16 bit mask. However I do not know how to create a 32 bit mask using this approach. Any ideas?
edit: I want to create 32 masks of 32 bits, each with with its respective bit being 1 and the rest of the bits being zero. For example: mask 1 has the leftmost bit being 1 while the rest of the bits are zero, mask 2 has the 2nd leftmost bit being 1 while the rest of the bits are zero. I dunno how to explain more succinctly but I hope you guys get the idea...
mask = new int[16];
mask[0] = 0x8000;
mask[1] = 0x4000;
mask[2] = 0x2000;
mask[3] = 0x1000;
mask[4] = 0x0800;
mask[5] = 0x0400;
mask[6] = 0x0200;
mask[7] = 0x0100;
mask[8] = 0x0080;
mask[9] = 0x0040;
mask[10] = 0x0020;
mask[11] = 0x0010;
mask[12] = 0x0008;
mask[13] = 0x0004;
mask[14] = 0x0002;
mask[15] = 0x0001

Here's how to create a 32 bit mask in Java.
int mask = 0x00010000; // for example.
And if you want to create a 32 bit mask with bit N set then
int mask = 1 << N; // Assumes the rightmost bit is numbered zero ...
And if you want to create an array of masks, then just do the above in a loop, in the obvious fashion.
int[] masks = new int[32];
for (int n = 0; n < 32; n++) {
masks[n] = 1 << n;
}
In reality, your supposed "16 bit masks" are also 32 bit masks, because int is a 32 bit type in Java.
And like #Matt Ball, I'm puzzled as to what you are really trying to do, and whether you are going about it is a sensible way to achieve it. Why do you need an array of masks when you can create a mask on the fly with less code?

I think you are doing well.
AMOUNT_OF_BITS = 32;
mask = new long[AMOUNT_OF_BITS];
for (long i = 0; i < AMOUNT_OF_BITS; i++)
{
mask[i] = Math.pow(2,i);
}
This should work, I think.

Related

How to change the most significant bit to a 1 after shifting an int to the right using '>>'?

For example, when I have a number such as 0x54 in binary that would be 01010100. After using the bit-wise operator '>>' this number will turn into 00101010. Instead of the most significant bit being a 0, I need it to be a one. How can i accomplish this?
Is your number always 8 bits wide? If thats the case you can simply have the decimal representation of 10000000 which is 128 and do a bitwise or
so let's take your example
int val = 84; /// 01010100
int newVal = val >> 1; // 00101010
int mostSig = newVal | 128; // 10101010

Java - Copy integer to long

I have an external system outputting 2 unsigned integers that represent a 64 bit unsigned int. Java picks these up and converts them to signed integers. I have called them lower and upper in java. I would like to put this back into a 64 bit int. I understand I have to use signed int which is ok.
I started off casting them both to long, shift the upper long by 32 bits and then trying to add them but it didn't go so well because the cast moves the sign bit of the integers. So I started to muck around with adding 2^31 and other messy stuff. How can I do this cleanly?
Here is an example, using 2 x 8 bit numbers to 16 bits for simplicity
Higher = 00000000 lower = 11111111
Desired result
0000000011111111
Result I get
1000000001111111
EDIT: This is code that I believe works ok (I haven't fully tested) but I was hoping for something cleaner.
private static long combineCounters(int lower, int upper) {
long lower2 = (long)lower;
if(lower2 < 0) lower2 += (2L<<31);
long upper2 = (long)upper;
if(upper2 < 0) upper2 += (2L<<31);
long result = lower2 | (upper2<<32);
return result;
}
For your case, first of all, you should store your integer values correctly into a long. To do so, you can AND your value with 0xFFFFFFFFL (a long with first 32 bit as 1).
Here is an example which works:
int upperInt = ...
int lowerInt = ...
long hi = upperInt & 0xFFFFFFFFL;
long lo = lowerInt & 0xFFFFFFFFL;
long c = (hi << 32) | lo;
System.out.println(String.format("0x%X", c));
int higher = ...
int lower = ...
long result = (((long) higher) << 32) | ((long) lower) & 0xFFFFFFFFL;

What does this binary documentation mean?

I'm trying to decode somebody's byte array and I'm stuck at this part:
&lt state &gt ::= "01" <i>(2 bits) for A</i>
"10" <i>(2 bits) for B</i>
"11" <i>(2 bits) for C</i>
I think this wants me to look at the next 2 bits of the next byte. Would that mean the least or most significant digits of the byte? I suppose I would just throw away the last 6 bits if it means the least significant?
I found this code for looking at the bits of a byte:
for (int i = 0; i < byteArray.Length; i++)
{
byte b = byteArray[i];
byte mask = 0x01;
for (int j = 0; j < 8; j++)
{
bool value = b & mask;
mask << 1;
}
}
Can someone expand on what this does exactly?
Just to give you a start:
To extract individual bits of a byte, you use "&", called the bitwise and operator. The bitwise and operation means "preserve all bits which are set on both sides". E.g. when you calculate the bitwise-and of two bytes, e.g. 00000011 & 00000010, then the result is 00000010, because only the bit at the second last position is set in both sides.
In java programming language, the very same example looks like this:
int a = 3;
int b = 2;
int bitwiseAndResult = a & b; // bitwiseAndResult will be equal to 2 after this
Now to examine if the n'th bit of some int is set, you can do this:
int intToExamine = ...;
if ((intToExamine >> n)) & 1 != 0) {
// here we know that the n'th bit was set
}
The >> is called the bitshift operator. It simply shifts the bits from left to right, like this: 00011010 >> 2 will have the result 00000110.
So from the above you can see that for extracting the n'th bit of some value, you first shift the n'th bit to position 0 (note that the first bit is bit 0, not bit 1), and then you use the bitwise and operator (&) to only keep that bit 0.
Here are some simple examples of bitwise and bit shift operators:
http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm

Java Long - Bit's manipulation

I have a long number and I want to manipulate it bits in following way:
Long l = "11000000011" (long l 's bit representation)
Long ll1 = "110000000" (remove last two bits from l and convert to Long)
Long ll2 = "11" (keep last two bit's of l and discard other bits and convert to Long)
Can anybody help me, how to do this in Java in a fast way ?
To convert a string of bits into a long, you can use Long.parseLong:
long l = Long.parseLong("11000000011", 2);
You can then use the bit-shifting operators >>, <<, and >>> to drop off the lower bits. For example:
long ll1 = l >>> 2;
To drop off all but the top two bits, you can use Long.bitCount to count the bits, then shift off the remaining bits.
long ll2 = l >>> (Long.bitCount(ll1) - 2);
EDIT: Since the question you're asking has to do with going from longs to the bits of the longs, you should use the Long.toBinaryString method for this:
String bits = Long.toBinaryString(/* value */);
From there, to drop off the last two bits you can use simple string manipulation. Try using String.substring for this.
Hope this helps!
long l = Long.parseLong("11110", 2) ;
long ll1 = l >>> 2;
long lb = (l & 1) ; last bit
long ls = l >>> 1;
long lb1 = (ls & 1) ; bit before last bit

Set a BitSet as a primitive type?

In Java, can you create a BitSet of size 8 and store it as a byte in order to output it? The documentation on BitSets doesn't mention it. Does that mean no?
You can't cast BitSet to byte.
You can write code to do what you want though. Given a BitSet named bits, here you go:
byte output = 0;
for (int i = 0; i < 8; i++) {
if (bits.get(i)) {
output |= 1 << (7 - i);
}
}
Update: The above code assumes that your bits are indexed 0 to 7 from left to right. E.g. assuming the bits 01101001 you consider bit 0 to be the leftmost 0. If however you're assigning the bits from right to left then bit 0 would be the rightmost 1. In which case you want output |= 1 << i instead.
There's nothing built in for that. You could implement that yourself obviously.
bit set is an array of bits
the JVM uses a 32-bit stack cell ie each register in the JVM stores one 32-bit address
we know that primitive boolean is set to be 1 bit but handled as 32 bit. array of boolean will be considered to be array of bytes
in BitSet each component of the bit set has a boolean value
Every bit set has a current size,
which is the number of bits of space
currently in use by the bit set. Note
that the size is related to the
implementation of a bit set, so it may
change with implementation. The length
of a bit set relates to logical length
of a bit set and is defined
independently of implementation.
The BitSet class is obviously not intended to export or import its bits to native datatypes and also quite heavy if you just want to deal with the fixed size of a single byte. It might thus not be what you need if you just want to manipulate the bits of a byte independently and then use the resulting byte. It seems you might just want to use a API like this:
SimpleBitSet bs = new SimpleBitSet( 'A' );
bs.setBit( 5 );
byte mybyte = bs.getByte();
So a implementation of such a simplified bit set could look like this:
public class SimpleBitSet
{
private byte bits;
public SimpleBitSet( int bits )
{
this.bits = (byte) bits;
}
public byte getByte()
{
return bits;
}
public boolean getBit( int idx )
{
checkIndex( idx );
return ( bits & ( 1 << idx ) ) != 0;
}
public void setBit( int idx )
{
checkIndex( idx );
bits |= 1 << idx;
}
public void clearBit( int idx )
{
checkIndex( idx );
bits &= ~( 1 << idx );
}
protected void checkIndex( int idx )
{
if( idx < 0 || idx > 7 )
throw new IllegalArgumentException( "index: " + idx );
}
}

Categories