Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a bitset membership predicate which should handle all values of x:
int Contains(unsigned int A, int x)
{
return (x >= 0) && (x < 8 * sizeof A) && (((1u << x) & A) != 0);
}
Is there a more efficient implementation?
You can skip lower bound check if x is unsigned.
From N1570:
6.3.1.3 Signed and unsigned integers
When a value with integer type is converted to another integer type other than _Bool, if
the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type. 60)
unsigned int y = x; // Wrap around if x is negative
return (y < CHAR_BIT * sizeof A) && (1u << y & A) != 0;
Not sure if this really brings any meaningful improvement though. Check your compiler output to make sure.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to convert float negative values to unsigned int values. Is it possible?
For example:
float x = -10000.0;
int y;
y = x;
When we assign x value to y, can the negative value be stored in an integer?
If not, how can we store the negative values into integer variables?
can the negative (float f) value be stored in an integer?
Yes, with limitations.
With a signed integer type like int16_t i, i = f is well defined for
-32768.999... to 32767.999...
With an unsigned integer type like unt16_t u, u = f is well defined for
-0.999... to 65535.999...
The result is a truncated value (fraction thrown away). All other float values result in undefined behavior.
If not, how can we store the negative values into integer variables?
Best to use wide signed integer types and test for range limitations.
In any case, the fraction of the float is lost. A -0.5f can be stored in an unsigned, yet the value becomes 0u.
The below performs some simply tests to insure y is in range.
#include <limits.h>
float x = ...;
int y = 0;
if (x >= INT_MAX + 1u) puts("Too pos");
else if (x <= INT_MIN - 1.0) puts("Too neg");
else y = (int) x;
Note the tests above are illustrative as they lack high portability.
Example: INT_MIN - 1.0 in inexact in select situations.
To cope, with common 2's complement int, the below is better reformed. As 2's complement, INT_MIN is a power of 2 (negated) and usually in the range of float, thus making for an exact subtraction near the negative threshold. `
// if (x <= INT_MIN - 1.0)
if (x - INT_MIN <= - 1.0f)
Another alternative is to explore a union. Leave that for others to explain its possibilities and limitations.
union {
float f;
unsigned u;
} x;
float x = 10000.0;
int a;
a = (int)(x+0.5);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
What is the concept behind expressions like this?
int x;
x=7||6;
From the C11 draft specification
6.5.14 Logical OR operator
The || operator shall yield 1 if either of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.
So in the expression x = 7||6;, the || yields 1 because at least one (in fact both) of the operands compare unequal to 0.
int x;
x=7||6; // it is true always .
The output 1, you get is due to bool is promoted to int . As you can assume -
true==1
x = 7 || 6;
x = 7 "or" 6; //or can only apply to booleans
x = true or true; //Auto cast to booleans
x = true;
x = 1; //Auto cast to int
And please do some minimal effort in your class problems....
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Using only bit-wise and logical operations, how can I detect if any bit of x equals to 1 in C? No loops, if/else, ==, or !=
Someone proposed (x & ~0) && 1, but I've been looking at it for hours and still don't know how (x & ~0) && 1 can detect if any bit of x equals to 1
!!x will do it.
This will convert all values to 1, except for 0 which stays 0. And compilers can optimize this intelligently.
0 is a number with all its bits set to 0.
~ is bitwise NOT - it changes all 0 bits to 1 bits and 1 bits to 0 bits, so ~0 gives a number with all bits set to 1.
& is bitwise AND - & of two numbers returns a number where each bit corresponds to the logical AND of the corresponding bits in each of the numbers. Since ~0 consists of all 1 bits already, x & ~0 will simply return a number where each bit corresponds to the same bit in x, thus it will return x.
See Wikipedia on bitwise operations (AND and NOT) for more information.
Finally && is a boolean AND operator which will return 1 only if both sides are non-zero. 1 is not zero, thus it simply checks if (x & ~0) = x (as we established above) is not zero, thus if any of the bits in x are 1.
You should notice that there's a lot of redundancy going on here - as already pointed out, you can just use x instead.
Is this your class assignment?
You wrote "how can I detect ...", but what do you expect for the result of your "detection"?
If the result should be an integer to be fed to if/else, then you can directly feed the original x to if/else, because C's if/else can work with any integers and when "any bit of" the input equals 1, the then clause will be executed. Only when the input is exactly 0, the else clause will be executed. But if your question is your class assignment, this will not be the answer you're looking for.
If you want either 0 or 1 and don't want anything else, use #StilesCrisis's answer. Because
int y = ! x
is equivalent to
int y;
if (0 == x)
y = 1;
else
y = 0;
and therefore
int z = !! x
(whose verbose version is
int z = ! ( ! x )
) is equivalent to
int z;
if (0 == x)
z = 0;
else
z = 1;
Finally, (x & ~0) && 1 is as pointless as x + 0.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to write two functions that will check/prevent overflow in c (using only ! ~ | & ^ +) but cant get it. The first is will a certain twos compliment/signed int will fit in a certatin amount of bits: fitsB(int x, int n) where is the int and n is the size of bits to use. Also a function that will check to see if two ints will not overflow when added together: overflowInt(int x, int y). I can get it if they are unsigned ints but the negatives just make things harder for me. Anyone know how to?
There also is no casting and ints are always 32 bit
/*
* addOK - Determine if can compute x+y without overflow
* Example: addOK(0x80000000,0x80000000) = 0,
* addOK(0x80000000,0x70000000) = 1,
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int addOK(int x, int y) {
// Find the sign bit in each word
//if a and b have different signs, you cannot get overflow.
//if they are the same, check that a is different from c and b is different from c,
// if they are the same, then there was no overflow.
int z=x+y;
int a=x>>31;
int b=y>>31;
int c=z>>31;
return !!(a^b)|(!(a^c)&!(b^c));
}
x will fit in n bits if x < 2^(n-1).
The overflow question needs more information. Two ints will not overflow if you assign them to a long (or a double).
Using the above example (Adam Shiemke), you can find the maximum (positive) value and minimum value (negative) to get the range for n number of bits. 2^(n-1) (from Adam's example) and minus one for the maximum/positive number which can be represented in the n bits. For the minimum value, negate 2^(n-1) to get the minimum value x => -(2^(n-1)); (Note the >= not > for the minimum range). For example, for n = 4 bits, 2^(4-1) - 1 = 2^3 -1 = 7 so x <= 7 and x >= -8 = (-(2^(4-1)).
This assumes the initial input does not overflow a 32 bit quanity (Hopefully an error occurs in that condition) and the number of bits you are using is less then 32 (as you are adding 1 for the negative range and if you have 32 bits, it will overflow, see below for an explanation).
To determine if addition will overflow, if you have the maximum value, the x + y <= maximum value. By using algebra, we can get y <= maximum value - x. You can then compare the passed in value for y and if it does not meet the condition, the addition will overflow. For example if x is the maximumn value, then y <= 0, so y must be less then or equal to zero or the addition will overflow.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to append any static single digit in given number using bitwise operation.
Let the static number is 1 ,
If the number is
2 => 12
31 => 131
24 => 124
11 => 111
Is it possible to do..?
Here why I am strict with bitwise means , I want to maintain as integer values.
If your dbms supports basic math functions (Oracle for instance), you can use:
SELECT NUMBER + Power(10, Floor(Log(10, NUMBER)) + 1)
FROM TABLE;
If not you could get away with a string trick like:
SELECT TO_NUMBER('1' || TO_CHAR(NUMBER))
FROM TABLE;
(using Oracle)
Bitwise operators won't work that well on decimal numbers since powers of two and powers of ten don't mesh well (I have no idea what the database tag is for here, this seems to be totally unrelated).
If you want a function to add a 1 to the left of an arbitrary number as you seem to indicate, you can use the following algorithm:
def prefixWithOne (n):
if n == 0:
return 10
addNum = 1
testNum = n
while testNum > 0:
testNum = int (testNum / 10)
addNum = addNum * 10
return addNum + n
For example, the following C code will do that:
unsigned int prefixWithOne (unsigned int n) {
unsigned int testNum = n;
unsigned int addNum = 1;
if (n == 0) return 10;
while (testNum > 0) {
testNum /= 10;
addNum *= 10;
}
return addNum + n;
}
(with the usual caveats about watching out for overflow).