How does this program evaluate? [closed] - c

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.

Related

I need help understanding this code 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 7 years ago.
Improve this question
I'm studying C in school and I had this question, and I'm having trouble solving it.
What does the following code do?
#define N (100)
int main(void)
{
unsigned short i = 0;
unsigned long arr[2*N + 1];
unsigned long a = 0;
for (i = 0 ; i < N ; ++i) {
a ^= arr[i];
}
printf("%lu", a);
return 0;
}
It would be really helpful if you could explain it to me!
Thanks!
It's usually a good idea to explain what you understand, so we don't have to treat you as though you know nothing. Important note: This code behaves erratically. I'll discuss that later.
The exclusive or operator (^) produces its result by applying the following pattern to the binary representation of the numbers in question:
Where both operands (sides of the operator) contain different bits, the result will contain a 1 bit. For example, if the left hand side contains a right-most bit of 0 and the right hand side contains a right-most bit of 1, then the result will contain a right-most bit of 1.
Where both operands (sides of the operator) contain the same bit, the result will contain a 0.
So as an example, the operands of 15 ^ 1 have the following binary notation:
1111 ^
0001
... and the result of this exclusive or operation will be:
1110
Converted back to decimal, that's 14. Xor it with 1 again and you'll end up back at 15 (which is the property the silly xor swap takes advantage of).
The array[index] operator obtains the element within array at the position indicated by index.
The ^= operator is a compound operator. It combines the exclusive or and assignment operators. a ^= arr[i]; is roughly equivalent to a = a ^ arr[i];. That means: Calculate the exclusive or of a and arr[i], and assign it back into a.
for (i = 0 ; i < N ; ++i) /*
* XXX: Insert statement or block of code
*/
This denotes a loop, which will start by assigning the value 0 to i, will repeatedly execute the statement or block of code while i is less than N (100), incrementing i each time.
In summary, this code produces the exclusive or of the first 100 elements of the array arr. This is a form of crude checksum algorithm; the idea is to take a group of values and reduce them to a single value so that you can perform some form of integrity check on them later on, perhaps after they've been trasmited via the internet or an unreliable filesystem.
However, this code invokes undefined behaviour because it uses unspecified values. In order to avoid erratic behaviour such as unpredictable values or segfaults (or worse yet, situations like the heartbleed OpenSSL vulnerability) you need to make sure you give your variables values before you try to use those values.
The following declaration would explicitly initialise the first element to 42, and implicitly initialise all of the others to 0:
unsigned long arr[2*N + 1] = { 42 };
It is important to realise that the initialisation part of the declaration = { ... } is necessary if you want any elements not explicitly initialised to be zeroed.
this function will print unpredictable value.
because of unsigned long arr[2*N + 1]; arr is not initialized and it will have random content based on data on you memory.
a ^= arr[i]; is equal to a = a^arr[i]; so it will do this for multiple times (because of loop) and then it will print it.

How to use bit manipulation to find 5th bit, and to return number of 1 bits in an integer

Assume Z is an unsigned integer. Using ~, <<, >>, &, | , +, and - provide statements which return the desired result.
I am allowed to introduce new binary values if needed.
I have these problems:
1.Extract the 5th bit from the left Z.
For this I was thinking about doing something like
x x x x x x x x
& 0 0 0 0 1 0 0 0
___________________
0 0 0 0 1 0 0 0
Does this make sense for extracting the fifth bit? I am not totally sure how I would make this work by using just Z when I do not know its values. (I am relatively new to all of this). Would this type of idea work though?
2.Return the number of 1 bits in Z
Here I kind of have no idea how to work this out. What I really need to know is how to work on just Z with the operators, but I m not sure exactly how to.
Like I said I am new to this, so any help is appreciated.
Problem 1
You’re right on the money. I’d do an & and a >> so that you get either a nice 0 or 1.
result = (z & 0x08) >> 3;
However, this may not be strictly necessary. For example, if you’re trying to check whether the bit is set as part of an if conditional, you can exploit C’s definition of anything nonzero as true.
if (z & 0x08)
do_stuff();
Problem 2
There are a whole variety of ways to do this. According to that page, the following methodology dates from 1960, though it wasn’t published in C until 1988.
for (result = 0; z; result++)
z &= z - 1;
Exactly why this works might not be obvious at first, but if you work through a few examples, you’ll quickly see why it does.
It’s worth noting that this operation – determining the number of 1 bits in a number – is sufficiently important to have a name (population count or Hamming weight) and, on recent Intel and AMD processors, a dedicated instruction. If you’re using GCC, you can use the __builtin_popcount intrinsic.
Problem 1 looks right, except you should finish it by shifting the result right by 4 to get that bit after the mask.
To implement the mask, you need to know what integer is represented by a single 5th bit. That number is incidentally 2^5 = 32. So you can just AND z with 32 and shift it right by 4.
Problem 2:
int answer = 0;
while (z != 0){ //stop when there are no more 1 bits in z
//the following masks the lowest bit in z and adds it into answer
//if z ends with a 0, nothing is added, otherwise 1 is added
answer += (z & 1);
//this shifts z right by 1 to get the next higher bit
z >>= 1;
}
return answer;
To find out the value of the fifth bit, you don't care about the bottom bits so you can get rid of them:
unsigned int answer = z >> 4;
The fifth bit becomes the bottom bit, so you can strip it off with a bitwise-AND:
answer = answer & 1;
To find the number of 1-bits in a number you can apply stakSmashr's solution. You could optimise this further if you know you need to count the number of bits in a lot of integers - precompute the number of bits in every possible 8-bit number and store it in a table. There will only be 256 entries in the table so it won't use much memory. Then, you can loop over your data one byte at a time and find the answer from the table. This lookup will be quicker than looping again over each bit.

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;
}

Bitwise overflow checking in c [closed]

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.

Resources