Bitwise overflow checking in c [closed] - c

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.

Related

Whats a value of x such that both x + 1 == x and x * 2 == x is true? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Title basically says it all. My friend gave me this as a challenge he solved in some CTF he is doing. I have thought about it for a while and can not figure it out. Also, INFINITY isn't a valid answer. Thanks.
The only way this happens in C is:
x is an infinity (+∞ or −∞) (equivalently, HUGE_VAL or -HUGE_VAL in implementations that do not support infinities).
x is a NaN and the C implementation uses non-IEEE-754 behavior for NaNs.
x is adjacent to an infinity in the floating-point representation and a suitable directed rounding mode is used.
x+1 and x*2 overflow and the resulting behavior not defined by the C standard happens to report the comparisons as true.
x is uninitialized and hence indeterminate and takes on different values in the two appearances of x in x+1 == x such that the comparison is true and, in x*2 == x either similarly takes on different values or takes on the value zero.
x is uninitialized and has automatic storage duration and its address is not taken, and hence the behavior is not defined by the C standard, and the resulting behavior happens to report the comparisons as true.
Proof:
Other than infinity, the statements are mathematically false in real numbers, and therefore this cannot arise from real-number behavior. So it must arise from some non-real-number behavior such as overflow, wrapping, rounding, indeterminate values (which may be different in each use of an object) or uninitialized values. Since * is constrained to have arithmetic operands, we only need to consider arithmetic types. (In C++, one could define a class to make the comparisons true.)
For signed integers, non-real-number behavior with fully defined values occurs for + and * only when there is overflow, so that is a possibility.
For unsigned integers, non-real-number behavior with fully defined values occurs for + and * only when there is wrapping. Then, with wrapping modulo M, we would have x+1 = x+kM for some integer k, so 1 = kM, which is not possible for any M used in wrapping.
For the _Bool type, exhaustive testing of the possible values eliminates them.
For floating-point numbers, non-real-number behavior with fully defined values occurs for + and * only with rounding, underflow, and overflow and with NaNs. NaNs never compare as equal by IEEE-754 rules, so they cannot satisfy this, except for the fact that the C standard does not require IEEE-754 conformance, so an implementation could choose to make the comparisons true.
x*2 will not underflow, since it increases the magnitude. x+1 can be made to underflow in a perverse floating-point format with smaller exponent range than precision, but this will not produce x+1 == x. x+1 == x can be satisfied by rounding for sufficiently large x, but then x*2 must produce a value other than x.
That leaves overflow. If x is the greatest representable finite number (and hence the greatest representable number less than infinity), and the rounding mode is downward (toward −∞) or toward zero, then x+1 will yield x and x*2 will yield x, so the comparisons yield true. Similarly, the greatest negative representable finite number will satisfy the comparisons with rounding upward (toward +∞) or toward zero.
The equalities will hold true for double x = HUGE_VAL;. Since C99, quoting cppreference.com:
The HUGE_VALF, HUGE_VAL and HUGE_VALL macros expand to positive floating point constant expressions which compare equal to the values returned by floating-point functions and operators in case of overflow
Sample code:
#include <math.h>
#include <stdio.h>
int main() {
double x = HUGE_VAL;
printf("%d %d\n", x + 1 == x, 2 * x == x);
return 0;
}
Output:
1 1
Solving for x using the C preprocessor:
#include <stdio.h>
int main() {
#define x 1,1
if (x + 1 == x)
printf("x + 1 == x is true\n");
if (x * 2 == x)
printf("x * 2 == x is true\n");
printf("x = %d\n", x);
printf("x + 1 = %d\n", x + 1);
printf("x * 2 = %d\n", x * 2);
return 0;
}
Output (warnings omitted :):
x + 1 == x is true
x * 2 == x is true
x = 1
x + 1 = 1
x * 2 = 1

how do I find if any bit of x equals 1 in C [closed]

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.

In C bits, multiply by 3 and divide by 16

A buddy of mine had these puzzles and this is one that is eluding me. Here is the problem, you are given a number and you want to return that number times 3 and divided by 16 rounding towards 0. Should be easy. The catch? You can only use the ! ~ & ^ | + << >> operators and of them only a combination of 12.
int mult(int x){
//some code here...
return y;
}
My attempt at it has been:
int hold = x + x + x;
int hold1 = 8;
hold1 = hold1 & hold;
hold1 = hold1 >> 3;
hold = hold >> 4;
hold = hold + hold1;
return hold;
But that doesn't seem to be working. I think I have a problem of losing bits but I can't seem to come up with a way of saving them. Another perspective would be nice. Just to add, you also can only use variables of type int and no loops, if statements or function calls may be used.
Right now I have the number 0xfffffff. It is supposed to return 0x2ffffff but it is returning 0x3000000.
For this question you need to worry about the lost bits before your division (obviously).
Essentially, if it is negative then you want to add 15 after you multiply by 3. A simple if statement (using your operators) should suffice.
I am not going to give you the code but a step by step would look like,
x = x*3
get the sign and store it in variable foo.
have another variable hold x + 15;
Set up an if statement so that if x is negative it uses that added 15 and if not then it uses the regular number (times 3 which we did above).
Then divide by 16 which you already showed you know how to do. Good luck!
This seems to work (as long as no overflow occurs):
((num<<2)+~num+1)>>4
Try this JavaScript code, run in console:
for (var num = -128; num <= 128; ++num) {
var a = Math.floor(num * 3 / 16);
var b = ((num<<2)+~num+1)>>4;
console.log(
"Input:", num,
"Regular math:", a,
"Bit math:", b,
"Equal: ", a===b
);
}
The Maths
When you divide a positive integer n by 16, you get a positive integer quotient k and a remainder c < 16:
(n/16) = k + (c/16).
(Or simply apply the Euclidan algorithm.) The question asks for multiplication by 3/16, so multiply by 3
(n/16) * 3 = 3k + (c/16) * 3.
The number k is an integer, so the part 3k is still a whole number. However, int arithmetic rounds down, so the second term may lose precision if you divide first, And since c < 16, you can safely multiply first without overflowing (assuming sizeof(int) >= 7). So the algorithm design can be
(3n/16) = 3k + (3c/16).
The design
The integer k is simply n/16 rounded down towards 0. So k can be found by applying a single AND operation. Two further operations will give 3k. Operation count: 3.
The remainder c can also be found using an AND operation (with the missing bits). Multiplication by 3 uses two more operations. And shifts finishes the division. Operation count: 4.
Add them together gives you the final answer.
Total operation count: 8.
Negatives
The above algorithm uses shift operations. It may not work well on negatives. However, assuming two's complement, the sign of n is stored in a sign bit. It can be removed beforing applying the algorithm and reapplied on the answer.
To find and store the sign of n, a single AND is sufficient.
To remove this sign, OR can be used.
Apply the above algorithm.
To restore the sign bit, Use a final OR operation on the algorithm output with the stored sign bit.
This brings the final operation count up to 11.
what you can do is first divide by 4 then add 3 times then again devide by 4.
3*x/16=(x/4+x/4+x/4)/4
with this logic the program can be
main()
{
int x=0xefffffff;
int y;
printf("%x",x);
y=x&(0x80000000);
y=y>>31;
x=(y&(~x+1))+(~y&(x));
x=x>>2;
x=x&(0x3fffffff);
x=x+x+x;
x=x>>2;
x=x&(0x3fffffff);
x=(y&(~x+1))+(~y&(x));
printf("\n%x %d",x,x);
}
AND with 0x3fffffff to make msb's zero. it'l even convert numbers to positive.
This uses 2's complement of negative numbers. with direct methods to divide there will be loss of bit accuracy for negative numbers. so use this work arround of converting -ve to +ve number then perform division operations.
Note that the C99 standard states in section section 6.5.7 that right shifts of signed negative integer invokes implementation-defined behavior. Under the provisions that int is comprised of 32 bits and that right shifting of signed integers maps to an arithmetic shift instruction, the following code works for all int inputs. A fully portable solution that also fulfills the requirements set out in the question may be possible, but I cannot think of one right now.
My basic idea is to split the number into high and low bits to prevent intermediate overflow. The high bits are divided by 16 first (this is an exact operation), then multiplied by three. The low bits are first multiplied by three, then divided by 16. Since arithmetic right shift rounds towards negative infinity instead of towards zero like integer division, a correction needs to be applied to the right shift for negative numbers. For a right shift by N, one needs to add 2N-1 prior to the shift if the number to be shifted is negative.
#include <stdio.h>
#include <stdlib.h>
int ref (int a)
{
long long int t = ((long long int)a * 3) / 16;
return (int)t;
}
int main (void)
{
int a, t, r, c, res;
a = 0;
do {
t = a >> 4; /* high order bits */
r = a & 0xf; /* low order bits */
c = (a >> 31) & 15; /* shift correction. Portable alternative: (a < 0) ? 15 : 0 */
res = t + t + t + ((r + r + r + c) >> 4);
if (res != ref(a)) {
printf ("!!!! error a=%08x res=%08x ref=%08x\n", a, res, ref(a));
return EXIT_FAILURE;
}
a++;
} while (a);
return EXIT_SUCCESS;
}

How does this program evaluate? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
#include <stdio.h>
void showbits(unsigned int x)
{
int i;
for(i=(sizeof(int)*8)-1; i>=0; i--)
(x&(1<<i))?putchar('1'):putchar('0');
printf("\n");
}
int main()
{
int j = 5225, m, n;
printf("The decimal %d is equal to binary - ", j);
/* assume we have a function that prints a binary string when given
a decimal integer
*/
showbits(j);
/* the loop for right shift operation */
for ( m = 0; m <= 5; m++ ) {
n = j >> m;
printf("%d right shift %d gives ", j, m);
showbits(n);
}
return 0;
}
Please explain it in detail. Like why is it written 1<<i instead of i>>1???
How will the condition evaluate for various binary numbers???
The expression x << y means "x shifted to the left by y number of bits". 1 << i will return an integer with bit i set to 1 and all other bits set to 0.
(i >> 1, on the other hand, means "shift i to the right by one bit". They're not comparable operations at all. Suppose i is 5: 1 << i will return the binary number 00100000, or 32, whereas i >> 1 will return the binary number 00000010, or 2.)
x & (1 << i) will perform a bitwise AND operation on x and 1 << i, which amounts to checking whether x has bit i set to 1. If it does, this will return a positive number; if not, it will return 0.
So the overall result of this expression will be to print the character 1 if x has bit i set to 1, and print 0 if it does not.
The author used the ternary operator ?: instead of if-then-else which would communicate clearer.
1<<i is a 1-bit shifted to a higher significance, example i=3: 0001b becomes 1000b.
This shifted set bit is then used to test the bit in x at that bit-position.
If that bit in x is 1 then the first putchar is evaluated, else the second.
why is it written 1<<i instead of i>>1???
1 << i means: Shift the the bit 1 left n-times. So the bit is set at position 0 and then shifted how often it is indicated by the value of i. Each successive shift operation constitutes a multiply by 2.
i>>1 This is quite a different operation, because it shifts the bits right and the operators are reversed, so this means shift the value in i right for one position. This is essentialy a division by 2.
These bit shift operation scan be used for some specific things. For example, they were used for fast multiplicactions/divisions of int for known numbers, because these operations are faster than doing an FPU operation for register sized values.
Another usage is to keep various bits in a single byte and mask them to test if they are set, or if you want to set them. In older times, this was often used to preserve memory (when memory was small and expensive). It is still needed on hardware devices, because there you often have hardware registers signaling various states in individual bits.
It just outputs the bitpattern of x to the screen, but in inverted order, that means if e.g. x is char and x == 5 then it prints: 10100000 (instead of 00000101). It is done by 1<<i and not 1>>i to not have to set i to the most significant bit depending on which type x has.
But you could write:
( x & (1<<(sizeof(x)*8-1-i)) ) ? putchar('1') : putchar('0');
Then you would have it in the right order.

Multiply two overflowing integers modulo a third

Given three integers, a, band c with a,b <= c < INT_MAX I need to compute (a * b) % c but a * b can overflow if the values are too large, which gives the wrong result.
Is there a way to compute this directly through bithacks, i.e. without using a type that won't overflow for the values in question?
Karatsuba's algorithm is not really needed here. It is enough to split your operands just once.
Let's say, for simplicity's sake, that your numbers are 64-bit unsigned integers. Let k=2^32. Then
a=a1+k*a2
b=b1+k*b2
(a1+k*a2)*(b1+k*b2) % c =
a1*b1 % c + k*a1*b2 % c + k*a2*b1 % c + k*k*a2*b2 % c
Now a1*b1 % c can be computed immediately, the rest could be computed by alternately performing x <<= 1 and x %= c 32 or 64 times (since (u*v)%c=((u%c)*v)%c). This could ostensibly overflow if c >= 2^63. However, the nice thing is that this pair of operations need not be performed literally. Either x < c/2 and then you only need a shift (and there's no overflow), or x >= c/2 and
2*x % c = 2*x - c = x - (c-x).
(and there's no overflow again).
Several of the major compilers offer a 128-bit integer type, with which you can do this computation without overflow.

Resources