Get the position of a bit and if it is set - java

I have a function which checks, whether a bit in an int is set or not.
But I think there will be a much faster implementation, since this one is linear and can't be the most efficient one, although I know the int should be between 1 and 1024.
public static int getBitPos(final int n) {
if (Integer.bitCount(n) != 1)
return Constants.UNDEFINED;
else {
for (int i = 0; i < Integer.MAX_VALUE; ++i) {
if (testBit(n, i))
return i;
}
}
return Constants.UNDEFINED;
}
Where testBit is the following standard function:
public static boolean testBit(final int n, final int pos) {
int mask = 1 << pos;
return (n & mask) == mask;
}
But there mast be a faster way, isn't there? If I have the value 17 and I want to know if the 4th bit (n = 8) is set? There should be a faster way to check whether the bit for n=8 is set...
Hope you can help me...
EDIT 1:
Thanks for the support. The comments and answers brought me to my mistake. I was setting the values wrongly, which made it more complicated than needed. I was never good at bit shifting.
I set the value like this, if I wanted the second bit to be set:
value = 2;
If I wanted the 4th bit to be set too, I added the value according to the 4th bit:
value += 8;
So value was 10, and the 2nd and 4th bit were set. So I saved the numbers in my class, instead of the bit-positions (8 as value, instead of 4 for the 4th bit, ...).
After changing this, I could get rid of my unnecessary function, which was way over the top!
Thanks for all help!

Your code always returns the lowest bit that is 1, if there is only one. You can achieve the same by doing this:
int foo = whatever;
int lowestSetBit = Integer.numberOfTrailingZeros(foo) + 1;
Your code would be
public static int getBitPos(final int n) {
if (Integer.bitCount(n) == 1)
return Integer.numberOfTrailingZeros(n) + 1;
return Constants.UNDEFINED;
}

Related

How to calculate the number of zeros in binary?

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

decimal to binary conversion java

My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}
An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for
As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.

Check partially known integer lies within a range

I have a peculiar problem for which I am looking for an efficient solution. I have a byte array which contains the most significant n bytes of an unsigned 4 byte integer (most sig byte first). The value of the remaining bytes (if any) are unknown. I need to check whether the partially known integer value could fall within a certain range (+ or - x) of a known integer. It's also valid for the integer represented by the byte array under test to wrap around.
I have a solution which works (below). The problem is that this solution performs way more comparisons than I believe is necessary and a whole load of comparisons will be duplicated in the scenario in which least sig bytes are unknown. I'm pretty sure it can be done more efficiently but can't figure out how. The scenario in which least significant bytes are unknown is an edge case so I might be able to live with it but it forms part of a system which needs to have low latency so if anyone could help with this that would be great.
Thanks in advance.
static final int BYTES_IN_INT = 4;
static final int BYTE_SHIFT = 010;
// partial integer byte array length guaranteed to be 1-4 so no checking necessary
static boolean checkPartialIntegerInRange(byte[] partialIntegerBytes, int expectedValue, int range)
{
boolean inRange = false;
if(partialIntegerBytes.length == BYTES_IN_INT)
{
// normal scenario, all bytes known
inRange = Math.abs(ByteBuffer.wrap(partialIntegerBytes).getInt() - expectedValue) <= range;
}
else
{
// we don't know least significant bytes, could have any value
// need to check if partially known int could lie in the range
int partialInteger = 0;
int mask = 0;
// build partial int and mask
for (int i = 0; i < partialIntegerBytes.length; i++)
{
int shift = ((BYTES_IN_INT - 1) - i) * BYTE_SHIFT;
// shift bytes to correct position
partialInteger |= (partialIntegerBytes[i] << shift);
// build up mask to mask off expected value for comparison
mask |= (0xFF << shift);
}
// check partial int falls in range
for (int i = -(range); i <= range; i++)
{
if (partialInteger == ((expectedValue + i) & mask))
{
inRange = true;
break;
}
}
}
return inRange;
}
EDIT: Thanks to the contributors below. Here is my new solution. Comments welcome.
static final int BYTES_IN_INT = 4;
static final int BYTE_SHIFT = 010;
static final int UBYTE_MASK = 0xFF;
static final long UINT_MASK = 0xFFFFFFFFl;
public static boolean checkPartialIntegerInRange(byte[] partialIntegerBytes, int expectedValue, int range)
{
boolean inRange;
if(partialIntegerBytes.length == BYTES_IN_INT)
{
inRange = Math.abs(ByteBuffer.wrap(partialIntegerBytes).getInt() - expectedValue) <= range;
}
else
{
int partialIntegerMin = 0;
int partialIntegerMax = 0;
for(int i=0; i < BYTES_IN_INT; i++)
{
int shift = ((BYTES_IN_INT - 1) - i) * BYTE_SHIFT;
if(i < partialIntegerBytes.length)
{
partialIntegerMin |= (((partialIntegerBytes[i] & UBYTE_MASK) << shift));
partialIntegerMax = partialIntegerMin;
}
else
{
partialIntegerMax |=(UBYTE_MASK << shift);
}
}
long partialMinUnsigned = partialIntegerMin & UINT_MASK;
long partialMaxUnsigned = partialIntegerMax & UINT_MASK;
long rangeMinUnsigned = (expectedValue - range) & UINT_MASK;
long rangeMaxUnsigned = (expectedValue + range) & UINT_MASK;
if(rangeMinUnsigned <= rangeMaxUnsigned)
{
inRange = partialMinUnsigned <= rangeMaxUnsigned && partialMaxUnsigned >= rangeMinUnsigned;
}
else
{
inRange = partialMinUnsigned <= rangeMaxUnsigned || partialMaxUnsigned >= rangeMinUnsigned;
}
}
return inRange;
}
Suppose you have one clockwise interval (x, y) and one normal interval (low, high) (each including their endpoints), determining whether they intersect can be done as (not tested):
if (x <= y) {
// (x, y) is a normal interval, use normal interval intersect
return low <= y && high >= x;
}
else {
// (x, y) wraps
return low <= y || high >= x;
}
To compare as unsigned integers, you can use longs (cast up with x & 0xffffffffL to counteract sign-extension) or Integer.compareUnsigned (in newer versions of Java) or, if you prefer you can add/subtract/xor both operands with Integer.MIN_VALUE.
Convert your unsigned bytes to an integer. Right-shift by 32-n (so your meaningful bytes are the min bytes). Right-shift your min/max integers by the same amount. If your shifted test value is equal to either shifted integer, it might be in the range. If it's between them, it's definitely in the range.
Presumably the sign bit on your integers is always zero (if not, just forcibly convert the negative to zero, since your test value can't be negative). But because that's only one bit, unless you were given all 32 bits as n, that shouldn't matter (it's not much of a problem in that special case).

Checking an int within range

Is there an elegant way in java to check if an int is equal to, or 1 larger/smaller than a value.
For example, if I check x to be around 5. I want to return true on 4, 5 and 6, because 4 and 6 are just one away from 5.
Is there a build in function to do this? Or am I better off writing it like this?
int i = 5;
int j = 5;
if(i == j || i == j-1 || i == j+1)
{
//pass
}
//or
if(i >= j-1 && i <= j+1)
{
//also works
}
Of course the above code is ugly and hard to read. So is there a better way?
Find the absolute difference between them with Math.abs
private boolean close(int i, int j, int closeness){
return Math.abs(i-j) <= closeness;
}
Based on #GregS comment about overflowing if you give Math.abs a difference that will not fit into an integer you will get an overflow value
Math.abs(Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 1
By casting one of the arguments to a long Math.abs will return a long meaning that the difference will be returned correctly
Math.abs((long) Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 4294967295
So with this in mind the method will now look like:
private boolean close(int i, int j, long closeness){
return Math.abs((long)i-j) <= closeness;
}
use Math.abs(x-5) <= 1 as a simple test. However, elegant is in the eye of the beholder. Strive for clarity instead.
Note than in general, for something like Glitch's fine answer or even this, there are overflow conditions that must be analyzed and understood. For correctness over all possible ints you should cast the arguments to long and perform the comparison using longs.

Number of zero bits in integer except leading zeros

If I have an integer in Java how do I count how many bits are zero except for leading zeros?
We know that integers in Java have 32 bits but counting the number of set bits in the number and then subtracting from 32 does not give me what I want because this will also include the leading zeros.
As an example, the number 5 has one zero bit because in binary it is 101.
Take a look at the API documentation of Integer:
32 - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n)
To count non-leading zeros in Java you can use this algorithm:
public static int countNonleadingZeroBits(int i)
{
int result = 0;
while (i != 0)
{
if (i & 1 == 0)
{
result += 1;
}
i >>>= 1;
}
return result;
}
This algorithm will be reasonably fast if your inputs are typically small, but if your input is typically a larger number it may be faster to use a variation on one of the bit hack algorithms on this page.
Count the total number of "bits" in your number, and then subtract the number of ones from the total number of bits.
This what I would have done.
public static int countBitsSet(int num) {
int count = num & 1; // start with the first bit.
while((num >>>= 1) != 0) // shift the bits and check there are some left.
count += num & 1; // count the next bit if its there.
return count;
}
public static int countBitsNotSet(int num) {
return 32 - countBitsSet(num);
}
Using some built-in functions:
public static int zeroBits(int i)
{
if (i == 0) {
return 0;
}
else {
int highestBit = (int) (Math.log10(Integer.highestOneBit(i)) /
Math.log10(2)) + 1;
return highestBit - Integer.bitCount(i);
}
}
Since evaluation order in Java is defined, we can do this:
public static int countZero(int n) {
for (int i=1,t=0 ;; i<<=1) {
if (n==0) return t;
if (n==(n&=~i)) t++;
}
}
Note that this relies on the LHS of an equality being evaluated first; try the same thing in C or C++ and the compiler is free to make you look foolish by setting your printer on fire.

Categories

Resources