Reputation: 3
I perform the operation for two integers... consider I do
A = (1 << 6) OR (1 << 7)
Is there a way that I can get the integers 6 and 7 from A after doing the OR operation?
Please let me know if the answer has been answered anywhere else.
Upvotes: 0
Views: 52
Reputation: 16050
Aside from the fact that your expression isn't valid Java and not knowing what you want to do, but assuming that you wish to ascertain which bits are "set", you can do this with Integer.numberOfTrailingZeros()
, eg.:
Integer.numberOfTrailingZeros( A & 64 ); // 1<<6 == 64
Integer.numberOfTrailingZeros( A & 128 ); // 1<<7 == 128
This would get you the ints 6 and 7 respectively.
Cheers,
Upvotes: 1
Reputation: 7518
If you are always bitshifting 1 then you can do the following.
int a = (1 << 6) ^ (1 << 7);
int temp = a;
for(int i=0;i<32;i++) {
if((temp&1)==1)
System.out.println("number: " + i);
temp = temp >> 1;
}
Output:
number: 6
number: 7
Upvotes: 0
Reputation: 298153
int value=(1<<7) | (1<<6);
StringBuilder sb=new StringBuilder();
if(value==0) sb.append("0");
else while(value!=0) {
int b=Integer.highestOneBit(value);
if(b==1) sb.append("1");
else
sb.append("(1<<").append(Integer.numberOfTrailingZeros(b)).append(')');
value-=b;
if(value>0) sb.append(" | ");
}
System.out.println(sb);
Upvotes: 0
Reputation: 43738
You can fetch the individual bits by testing them:
bit6 = (A >> 6) & 1;
bit7 = (A >> 7) & 1;
The integer 6 is in the bitset if bit6 == 1.
Upvotes: 0