How to find most significant bit (MSB) - java

I want to know which value the first bit of a byte has.
For example:
I have byte m = (byte) 0x8C;
How could I know if the first bit is an 1 or a 0 ?
Can anyone help me out ?

It depends what you mean by "first bit". If you mean "most significant bit" you can use:
// 0 or 1
int msb = (m & 0xff) >> 7;
Or if you don't mind the values being 0x80 or 0, just use:
// 0 or 0x80
int msb = m & 0x80;
Or in fact, as a boolean:
// Uses the fact that byte is signed using 2s complement
// True or false
boolean msb = m < 0;
If you mean the least significant bit, you can just use:
// 0 or 1
int lsb = m & 1;

If the first bit is the lowest bit (ie bit 0), then
if((m & 1) >0) ...
should do it.
In general,
if ((m & (1<<N)) > 0) ...
will give you whether or not bit N is set.
If, however, you meant the highest bit (bit 7), then use N=7.

Assuming you mean leftmost bit, bitwise and it with 0x80 and check if it is zero nor not:
public boolean isFirstBitSet(byte b) {
System.out.println((b & (byte)0x80));
return (b & (byte)0x80) < 0;
}
If you mean lowest order bit you will need to and with 0x01 and check a different condition:
public boolean isFirstBitSet(byte b) {
System.out.println((b & (byte)0x01));
return (b & (byte)0x80) > 0;
}

Use the bitwise and operator.
public class BitExample {
public static void main(String args[]) throws Exception {
byte m = (byte)0x8C;
System.out.println("The first bit is " + (m & (byte)0x01));
m = (byte)0xFF;
System.out.println("The first bit is " + (m & (byte)0x01));
}
}
// output is...
The first bit is 0
The first bit is 1

Its a bit of a hack but you can use
if(x >> -1 != 0) // top bit set.
This works for byte, short, int, long data types.
However for most types the simplest approach is to compare with 0
if (x < 0) // top bit set.
This works for byte, short, int, long, float, or double
(Ignoring negative zero and negative NaN, most people do ;)
For char type you need to know the number of bits. ;)
if (ch >>> 15 != 0) // top bit set.

This code gives you msb(most significant bit)/biggest number which is a
power of 2 and less than any given number.
class msb{
void main(){
int n=155;//let 110001010
int l=(Integer.toBinaryString(n)).length();//9
String w="0"+Integer.toBinaryString(i).substring(1);//010001010
i=Integer.parseInt(w,2);
System.out.println(n^i);//110001010^010001010=100000000
}
}

Related

Best way to check that in a binary representation of number all set bits are followed by unset bits only

Could you please let me know is there any best way to find that in binary representation of this number set bits are followed by unset bits only like -
4 - 100
6 - 110
8 - 1000
12 - 1100
private static boolean setBitFollowedByUnsetBits(int num) {
String str = Integer.toBinaryString(num);
int len = str.length();
int countof1 = str.indexOf('0');
int lastIndOf0 = str.lastIndexOf('0');
int countof0 = lastIndOf0 -countof1;
int lastIndOf1 = str.lastIndexOf('1');
if((!(lastIndOf1 > countof1) && (lastIndOf1 < lastIndOf0))) {
return ((num >> countof0+1)==((2 << countof1-1)-1));
}
return false;
}
This is what the logic i have written but i am looking for better solution which is much efficient .
Elaborating on #Alberto's hint:
You are looking for a bit pattern like 0000 0000 0111 1111 1100 0000 0000 0000 (I assume 32-bit integers):
some leading zero-bits (none is also OK)
a block of one-bits (at least one)
a block of zero-bits (at least one)
Special cases can be all zero-bits (N==0), or a number ending with a one-bit (having no trailing zero-bits). Let's first look at the generic case:
Having a binary number like N=xxxx1000, then N-1 is xxxx0111, replacing all the trailing zero-bits by one-bits, the rightmost one-bit by a zero-bit, and leaving the higher bits unchanged.
ORing N with N-1 like int K = N | (N-1); replaces trailing zero-bits with one-bits:
N = xxxx1000
N-1 = xxxx0111
--------
K = xxxx1111
We want the xxxx part to be something like 0001. Now, let's invert K:
~K = yyyy0000
where yyyy is the bitwise inverse of xxxx, and should look like 1110. So, once again, we can check for the trailing zero-bits and set them with int L = (~K) | ((~K)-1);. The result sould now be all one-bits if there was only one block of one-bits in the original number.
Now the special cases:
If there was no one-bit at all in N, the result will also give all ones. As the one-bits block is missing, the result should be false, needing a special handling.
A number consisting of just one block of one-bits will also result in all ones. But as the trailing zero-bits are missing, it should return false, needing a special handling as well, which just has to look at the last bit being zero.
So the code code look like:
private static boolean setBitFollowedByUnsetBits(int num) {
if (num == 0) return false;
if ((num & 1) == 1) return false;
int invK = ~ (num | (num-1));
int indicator = invK | (invK-1);
return indicator == 0xffffffff;
}
You could adapt Brian Kernigan's Algorithm
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
a) Initialize count: = 0
b) If integer n is not zero
Do bitwise & with (n-1) and assign the value back to n
{ n: = n&(n-1) }
Increment count by 1
go to step b
c) Else return count
As explained in the link above Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do bit-wise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
I think that more efficient way is to do bitwise checking instead of string -> integer transformation and operating with strings.
private static boolean check(int value) {
int h = SIZE - numberOfLeadingZeros(value);
boolean one = false;
boolean zero = false;
for (int i = h - 1; i >= 0; i--) {
int mask = 1 << i;
if ((value & mask) == mask) {
if (!zero) {
one = true;
} else {
return false;
}
} else {
if (one) {
zero = true;
} else {
return false;
}
}
}
return one && zero;
}
This is how I would do it.
private static boolean setBitFollowedByUnsetBits(int num) {
int withoutTrailingZeros = num >>> Integer.numberOfTrailingZeros(num);
return num != 0 && (withoutTrailingZeros & withoutTrailingZeros + 1) == 0;
}
This works because your problem is really to shift out the trailing zeros, which Java has a fast built in function for, then to test if the remaining number has all bits set (up to the most significant bit). You can do this with a bitwise and, as for any number n, n & n + 1 is only 0 if n has all bits set (see below). I assume you don't want 0 to return true because it has no bits set, but you can remove the num != 0 && if this isn't the case.
111 // 7
& 1000 // 8
= 0000 // 0, so 7 has all bits set
101 // 5
& 110 // 6
= 100 // 4, so 5 does not have all bits set
Edit: if the number must have some trailing zeros, you can also check for withoutTrailingZeros != num to be true.

Get bits of a given range more effective?

It's been a while, that I did bit manipulations and I'm not sure if this can be done in a more effective way.
What I want is to get bits of a specific range from a value.
Let's say the binary of the value is: 0b1101101
Now I want to get a 4-bit range from the 2nd to the 5th bit of this value in it's two's complement.
The range I wanna get: 0b1011
Value in Two's complement: -5
This is the code I have, with some thoughts what I'm doing:
public int bitRange(int value, int from, int to) {
// cut the least significant bits
value = value >> from;
// create the mask
int mask = 0;
for (int i = from; i <= to; i++) {
mask = (mask << 1) + 1;
}
// extract the bits
value = value & mask;
// needed to check the MSB of the range
int msb = 1 << (to - from);
// if MSB is 1, XOR and inverse it
if ((value & msb) == msb ) {
value = value ^ mask;
value = ~value;
}
return value;
}
Now I would like to know if this can be done more effective? Especially the creation of the dynamic mask and the check of the MSB of the range, to be able to convert the bit range. Another point is, as user3344003 pointed out correctly, if the range would be 1 bit, the output would be -1. I'm sure there is a possible improvement.
For your mask, you could go something like
int mask = 0xffffffff >> 32-(to-from);
Though the chance of that exact code being correct is small. Probably off by one, edge issues, sign problems. But it's on the right track?
Here's your mask:
int mask = 0xffffffff >>> 32 - (to - from + 1);
You have to use >>> due to sign bit is 1.
Another solution could be to store the possible masks which can be 31 values at the most:
private static int[] MASKS = new int[31];
static {
MASKS[0] = 1;
for (int i = 1; i < MASKS.length; i++)
MASKS[i] = (MASKS[i - 1] << 1) + 1;
}
And using this your mask:
int mask = MASKS[to - from];
You can do the same for the msb mask, just store the possible values in a static array, and you don't have to calculate it in your method.
Disclaimer: I'm more of a C or C++ programmer, and I know there are some subtles between the bitwise operators in the different languages. But it seems to me that this can be done in one line as follows by taking advantage of the arithmetic shift that will result when shifting a negative value to the right, where one's will be shifted in for the sign extension.
public int bitRange(int value, int from, int to) {
int waste = 31 - to;
return (value << waste) >> (waste + from);
}
breakdown:
int a = 31 - to; // the number of bits to throw away on the left
int b = value << a; // shift the bits to throw away off the left of the value
int c = a + from; // the number of bits that now need to be thrown away on the right
int d = b >> c; // throw bits away on the right, and extend the sign on the left
return d;

Confused About Bit Shifting (Counting Bits in Byte)

I'm trying to count the number of set bits in a byte but I appear to be running into some issues I can't find answers to.
My code currently looks like
public static int numBits(byte input){
int count = 0;
while (input != 0){
if ((input & 1)==1){
count++;
}
input >>= 1;
}
return count;
}
It appeared to work fine until I tried x = -1.
This ended up creating an infinite loop as value 1 bits were being inserted. So I stumbled upon
Java: right shift on negative number
which to my interpretation meant I should use input >>>= 1; but this still led to an infinite loop.
So I tried to figure out what was going on by trying
byte x = -1;
System.out.println(x >>> 1);
System.out.println(x >> 1);
which lead to
2147483647
-1
leaving me more confused. Where did the number 2147483647 come from and where might I be making a logic mistake?
The >>> operator means shift to the right, but do not sign-extend.
Your trial is pretty close, but you're not actually modifying x, so you can do:
int x = -1;
x = x >>> 1;
System.out.println(x);
x = x >> 1; // highest bit = 0 now
System.out.println(x);
Which will yield
2147483647
1073741823
Notice that I'm using int rather than byte here, since the result of bit shifts coerces the input to at least be integer sized.
Interestingly, when you run:
byte input = -1;
input = (byte) (input >>> 1);
The result is still -1. This is because of the type coercion happening with this operator mentioned above. To prevent this from affecting you, you can mask the bits of input to make sure you only take the first 8:
byte input = -1;
input = (byte) ((input & 0xFF) >>> 1);
Putting this together, if you were to run:
byte input = -1;
input = (byte) ((input & 0xFF) >>> 1);
System.out.println(input);
input = (byte) ((input & 0xFF) >> 1);
System.out.println(input);
You get the expected results:
127
63
This is all being caused by the way signed integers are stored as binary values. The way the highest bit of the number determines the sign (sort of—zero makes things weird), and the sign was being preserved with the arithmetic shift. Your print statements are giving weird results because the results are being promoted to int values instead of bytes.
If you want a really simple fix for this, you can just use an int to store your value, but make sure to mask off everything but the lowest-order byte:
public static int numBits(byte inByte){
int count = 0;
int input = inByte & 0xFF;
while (input != 0){
if ((input & 1)==1){
count++;
}
input >>= 1;
}
return count;
}
Like I said in my comment above, you should really read about Two's complement representation of signed numbers in binary. If you understand how negative numbers are represented, and the difference between arithmetic/logical shifts, all of that will make perfect sense.
You might find how the JVM actually does it is interesting. Note: there is only 8 bits so you don't really need a loop.
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
NOTE: On the x86/x64, the JVM replaces this with an intrinsic. i.e. it uses a single machine code instruction. If you copy this method and compare it will calling the original it is 3x slower as the JVM only replaces a hard coded list of methods, so it will replace Integer.bitCOunt, but not a copy.
In short, use the built in method instead of re-inventing it.

Bitwise operator for simply flipping all bits in an integer?

I have to flip all bits in a binary representation of an integer. Given:
10101
The output should be
01010
What is the bitwise operator to accomplish this when used with an integer? For example, if I were writing a method like int flipBits(int n);, what would go in the body? I need to flip only what's already present in the number, not all 32 bits in the integer.
The ~ unary operator is bitwise negation. If you need fewer bits than what fits in an int then you'll need to mask it with & after the fact.
Simply use the bitwise not operator ~.
int flipBits(int n) {
return ~n;
}
To use the k least significant bits, convert it to the right mask.
(I assume you want at least 1 bit of course, that's why mask starts at 1)
int flipBits(int n, int k) {
int mask = 1;
for (int i = 1; i < k; ++i)
mask |= mask << 1;
return ~n & mask;
}
As suggested by Lưu Vĩnh Phúc, one can create the mask as (1 << k) - 1 instead of using a loop.
int flipBits2(int n, int k) {
int mask = (1 << k) - 1;
return ~n & mask;
}
There is a number of ways to flip all the bit using operations
x = ~x; // has been mentioned and the most obvious solution.
x = -x - 1; or x = -1 * (x + 1);
x ^= -1; or x = x ^ ~0;
Well since so far there's only one solution that gives the "correct" result and that's.. really not a nice solution (using a string to count leading zeros? that'll haunt me in my dreams ;) )
So here we go with a nice clean solution that should work - haven't tested it thorough though, but you get the gist. Really, java not having an unsigned type is extremely annoying for this kind of problems, but it should be quite efficient nonetheless (and if I may say so MUCH more elegant than creating a string out of the number)
private static int invert(int x) {
if (x == 0) return 0; // edge case; otherwise returns -1 here
int nlz = nlz(x);
return ~x & (0xFFFFFFFF >>> nlz);
}
private static int nlz(int x) {
// Replace with whatever number leading zero algorithm you want - I can think
// of a whole list and this one here isn't that great (large immediates)
if (x < 0) return 0;
if (x == 0) return 32;
int n = 0;
if ((x & 0xFFFF0000) == 0) {
n += 16;
x <<= 16;
}
if ((x & 0xFF000000) == 0) {
n += 8;
x <<= 8;
}
if ((x & 0xF0000000) == 0) {
n += 4;
x <<= 4;
}
if ((x & 0xC0000000) == 0) {
n += 2;
x <<= 2;
}
if ((x & 0x80000000) == 0) {
n++;
}
return n;
}
faster and simpler solution :
/* inverts all bits of n, with a binary length of the return equal to the length of n
k is the number of bits in n, eg k=(int)Math.floor(Math.log(n)/Math.log(2))+1
if n is a BigInteger : k= n.bitLength();
*/
int flipBits2(int n, int k) {
int mask = (1 << k) - 1;
return n ^ mask;
}
One Line Solution
int flippingBits(int n) {
return n ^ ((1 << 31) - 1);
}
I'd have to see some examples to be sure, but you may be getting unexpected values because of two's complement arithmetic. If the number has leading zeros (as it would in the case of 26), the ~ operator would flip these to make them leading ones - resulting in a negative number.
One possible workaround would be to use the Integer class:
int flipBits(int n){
String bitString = Integer.toBinaryString(n);
int i = 0;
while (bitString.charAt(i) != '1'){
i++;
}
bitString = bitString.substring(i, bitString.length());
for(i = 0; i < bitString.length(); i++){
if (bitString.charAt(i) == '0')
bitString.charAt(i) = '1';
else
bitString.charAt(i) = '0';
}
int result = 0, factor = 1;
for (int j = bitString.length()-1; j > -1; j--){
result += factor * bitString.charAt(j);
factor *= 2;
}
return result;
}
I don't have a java environment set up right now to test it on, but that's the general idea. Basically just convert the number to a string, cut off the leading zeros, flip the bits, and convert it back to a number. The Integer class may even have some way to parse a string into a binary number. I don't know if that's how the problem needs to be done, and it probably isn't the most efficient way to do it, but it would produce the correct result.
Edit: polygenlubricants' answer to this question may also be helpful
I have another way to solve this case,
public static int complementIt(int c){
return c ^ (int)(Math.pow(2, Math.ceil(Math.log(c)/Math.log(2))) -1);
}
It is using XOR to get the complement bit, to complement it we need to XOR the data with 1, for example :
101 XOR 111 = 010
(111 is the 'key', it generated by searching the 'n' square root of the data)
if you are using ~ (complement) the result will depend on its variable type, if you are using int then it will be process as 32bit.
As we are only required to flip the minimum bits required for the integer (say 50 is 110010 and when inverted, it becomes 001101 which is 13), we can invert individual bits one at a time from the LSB to MSB, and keep shifting the bits to the right and accordingly apply the power of 2. The code below does the required job:
int invertBits (int n) {
int pow2=1, int bit=0;
int newnum=0;
while(n>0) {
bit = (n & 1);
if(bit==0)
newnum+= pow2;
n=n>>1;
pow2*=2;
}
return newnum;
}
import java.math.BigInteger;
import java.util.Scanner;
public class CodeRace1 {
public static void main(String[] s) {
long input;
BigInteger num,bits = new BigInteger("4294967295");
Scanner sc = new Scanner(System.in);
input = sc.nextInt();
sc.nextLine();
while (input-- > 0) {
num = new BigInteger(sc.nextLine().trim());
System.out.println(num.xor(bits));
}
}
}
The implementation from openJDK, Integer.reverse():
public static int More ...reverse(int i) {
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
Base on my experiments on my laptop, the implementation below was faster:
public static int reverse2(int i) {
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i & 0x00ff00ff) << 8 | (i >>> 8) & 0x00ff00ff;
i = (i & 0x0000ffff) << 16 | (i >>> 16) & 0x0000ffff;
return i;
}
Not sure what's the reason behind it - as it may depends on how the java code is interpreted into machine code...
If you just want to flip the bits which are "used" in the integer, try this:
public int flipBits(int n) {
int mask = (Integer.highestOneBit(n) << 1) - 1;
return n ^ mask;
}
public static int findComplement(int num) {
return (~num & (Integer.highestOneBit(num) - 1));
}
int findComplement(int num) {
int i = 0, ans = 0;
while(num) {
if(not (num & 1)) {
ans += (1 << i);
}
i += 1;
num >>= 1;
}
return ans;
}
Binary 10101 == Decimal 21
Flipped Binary 01010 == Decimal 10
One liner (in Javascript - You could convert to your favorite programming language )
10 == ~21 & (1 << (Math.floor(Math.log2(21))+1)) - 1
Explanation:
10 == ~21 & mask
mask : For filtering out all the leading bits before the significant bits count (nBits - see below)
How to calculate the significant bit counts ?
Math.floor(Math.log2(21))+1 => Returns how many significant bits are there (nBits)
Ex:
0000000001 returns 1
0001000001 returns 7
0000010101 returns 5
(1 << nBits) - 1 => 1111111111.....nBits times = mask
It can be done by a simple way, just simply subtract the number from the value
obtained when all the bits are equal to 1 .
For example:
Number: Given Number
Value : A number with all bits set in a given number.
Flipped number = Value – Number.
Example :
Number = 23,
Binary form: 10111
After flipping digits number will be: 01000
Value: 11111 = 31
We can find the most significant set bit in O(1) time for a fixed size integer. For
example below code is for a 32-bit integer.
int setBitNumber(int n)
{
n |= n>>1;
n |= n>>2;
n |= n>>4;
n |= n>>8;
n |= n>>16;
n = n + 1;
return (n >> 1);
}

Java: Checking if a bit is 0 or 1 in a long

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
I'd use:
if ((value & (1L << x)) != 0)
{
// The bit was set
}
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)
Another alternative:
if (BigInteger.valueOf(value).testBit(x)) {
// ...
}
I wonder if:
if (((value >>> x) & 1) != 0) {
}
.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.
Tom Hawtin - tackline Jul 7 at 14:16
You can also use
bool isSet = ((value>>x) & 1) != 0;
EDIT: the difference between "(value>>x) & 1" and "value & (1<<x)" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).
In that particular case, with "(value>>x) & 1" you will have the sign of value, whereas you get a 0 with "value & (1<<x)" (it is sometimes useful to get the bit sign if x is too large).
If you prefer to have a 0 in that case, you can use the ">>>" operator, instead if ">>"
So, "((value>>>x) & 1) != 0" and "(value & (1<<x)) != 0" are completely equivalent
For the nth LSB (least significant bit), the following should work:
boolean isSet = (value & (1 << n)) != 0;
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html
Bit shifting right by x and checking the lowest bit.
In Java the following works fine:
if (value << ~x < 0) {
// xth bit set
} else {
// xth bit not set
}
value and x can be int or long (and don't need to be the same).
Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of long) lowest bits of the right hand side operand. This implicitly translates the expression to value << (~x & 31) (or value << (~x & 63) if value is long).
Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any number is 32-bit.
Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).
How does it work?
The cleverness of this answer lies in that the sign bit of an integer is very easy to read: when that bit is set, then the value is negative; if not set, then the value is either zero or positive.
So the whole idea is to shift the xth bit exactly into the sign bit. That means a displacement of 31 - x to the left (or 63 - x, if value is 64 bits wide).
In java (and other languages as well), the ~ operator computes the bitwise NOT operation, which arithmetically equals to -x - 1 (no matter how wide x is).
Also the java << operator takes only the least significant 5 (or 6) bits of the right-hand side operand (whether 5 or 6 depends on how wide the left-hand side operand is: for int then 5; for long then 6). Arithmetically this is the same as the remainder of division by 32 (or 64).
And that is (-x - 1) % 32 = 31 - x (or (-x - 1) % 64 = 63 - x, for 64 bit wide value).
The value of the 2^x bit is "variable & (1 << x)"
My contribution - ignore previous one
public class TestBits {
public static void main(String[] args) {
byte bit1 = 0b00000001;
byte bit2 = 0b00000010;
byte bit3 = 0b00000100;
byte bit4 = 0b00001000;
byte bit5 = 0b00010000;
byte bit6 = 0b00100000;
byte bit7 = 0b01000000;
byte myValue = 9; // any value
if (((myValue >>> 3) & bit1 ) != 0) { // shift 3 to test bit4
System.out.println(" ON ");
}
}
}
If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.
1) Use java language functionality to get the binary format string and then check character at specific position
2) Keep dividing by 2 and decide the bit value at certain position.
public static void main(String[] args) {
Integer n =1000;
String binaryFormat = Integer.toString(n, 2);
int binaryFormatLength = binaryFormat.length();
System.out.println("binaryFormat="+binaryFormat);
for(int i = 1;i<10;i++){
System.out.println("isBitSet("+n+","+i+")"+isBitSet(n,i));
System.out.println((binaryFormatLength>=i && binaryFormat.charAt(binaryFormatLength-i)=='1'));
}
}
public static boolean isBitSet(int number, int position){
int currPos =1;
int temp = number;
while(number!=0 && currPos<= position){
if(temp%2 == 1 && currPos == position)
return true;
else{
temp = temp/2;
currPos ++;
}
}
return false;
}
Output
binaryFormat=1111101000
isBitSet(1000,1)false
false
isBitSet(1000,2)false
false
isBitSet(1000,3)false
false
isBitSet(1000,4)true
true
isBitSet(1000,5)false
false
isBitSet(1000,6)true
true
isBitSet(1000,7)true
true
isBitSet(1000,8)true
true
isBitSet(1000,9)true
true
declare a temp int and make it equal the original.
then shift temp >> x times, so that the bit you want to check is at the last position. then do temp & 0xf to drop the preceding bits. Now left with last bit. Finally do if (y & 1 == 0), if last bit is a 1, that should equal 0, else will equal 1. Its either that or if (y+0x1 == 0)... not too sure. fool around and see
I coded a little static class which is doing some of the bit operation stuff.
public final class Bitfield {
private Bitfield() {}
// ********************************************************************
// * TEST
// ********************************************************************
public static boolean testBit(final int pos, final int bitfield) {
return (bitfield & (1 << pos)) == (1 << pos);
}
public static boolean testNum(final int num, final int bitfield) {
return (bitfield & num) == num;
}
// ********************************************************************
// * SET
// ********************************************************************
public static int setBit(final int pos, final int bitfield) {
return bitfield | (1 << pos);
}
public static int addNum(final int number, final int bitfield) {
return bitfield | number;
}
// ********************************************************************
// * CLEAR
// ********************************************************************
public static int clearBit(final int pos, final int bitfield) {
return bitfield ^ (1 << pos);
}
public static int clearNum(final int num, final int bitfield) {
return bitfield ^ num;
}
}
If there are some questions flying around, just write me an email.
Good Programming!
Eliminate the bitshifting and its intricacies and use a LUT for the right and operand.

Categories

Resources