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 need to know how the output of the if statement is calculated true or false based on the following code:
#include <stdio.h>
enum designFlags {
BOLD = 8,
ITALICS = 9,
UNDERLINE = 4
};
int main() {
int myDesign = BOLD & ITALICS;
printf("%d", myDesign);
if(BOLD & ITALICS)
printf("Design is ITALIC");
else
printf("Design is not ITALIC");
return 0;
}
first go through any C books for operators.
if(BOLD & ITALICS )
'&' its a bitwise And operator . i.e it operates on bits
BOLD = 8 = 0000 1000
&
ITALICS = 9 = 0000 1001 (check the truth table of bitwise & )
-------------------------
= 0000 1000 =8
So if(8) means true so "Design is Italics" gets printed.
As per standard §6.8.4.1
the first substatement is executed if the expression compares unequal
to 0. In the else form, the second substatement is executed if the
expression compares equal to 0.
Here the result is 8 a nonzero so if statement is executed.
The bitwise and operator is applied between those two enum values resulting in the value of 8.
The name bitwise gives enough hint on how it works. You write down the binary and perform and operation bit by bit.
As per standard,§6.5.10
The result of the binary & operator is the bitwise AND of the
operands (that is, each bit in the result is set if and only if each
of the corresponding bits in the converted operands is set).
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 2 years ago.
Improve this question
Working with bits in C. I am trying to create a function that looks for a specific string of bits in a larger bit string. My thinking was to compare the two using the & operator, then shifting the string left and repeating. If the operator returns the larger number (because no bits should change), the pattern has been found. Unfortunately, that seems to be a flawed method, since what I have narrowed down to is that when this happens it in fact returns the smaller string, throwing what I thought I knew into doubt.
I suppose my guess is that the zeroes in front aren't in fact added when doing this operation, but i'm wary of rationalizing the wrong theory in my coding, so here I am. Please explain, none of the resources I have found really address what is going on here. Thanks in advance.
int main (void)
{
unsigned int x = 682; // 1010101010
unsigned int pattern = 42; // 101010
unsigned int temp;
temp = x & pattern;
printf("%i\n", temp);
return 0;
}
Because & compares the bits in bitwise order. For each pair of bits it will return 1 if both are 1 otherwise 0. The 42 in binary has an implicit set of zeros in front of it.
The comparison is
0000101010
1010101010
-----------
0000101010
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have been looking at some code that fills arrays with samples created using an IFFT (Inverse Fast Fourier Transform).
When the author iterates the array he uses an if construct that looks like this:
int idx;
for (idx = 1; idx < (tableLen >> 1); idx++) {
freqWaveRe[idx] = 1.0 / idx; // sawtooth spectrum
freqWaveRe[tableLen - idx] = -freqWaveRe[idx]; // mirror
}
Can you explain the terminating condition:
idx < (tableLen >> 1)
Why would you do something like this and what does it mean?
The bit shift operator used in this expression:
idx < (tableLen >> 1)
Terminates the for loop after iterating through the first half of the array. The right shift operator moves the value one bit to the right. Moving it one bit to the right divides it by two.
1010 in binary = 10
If we right shift it one bit we get:
0101 in binary = 5
A couple more things:
Tony D mentioned some comments made that this 'will not work well if idx is negative'. Negative numbers are represented differently. Sometimes negatives are stored with the first bit representing the sign. If you shift the sign right you will lose that information and cause a bit of a mess.
Tony D also said "it was historically an optimisation when bit-shifting opcodes executed faster than division, and optimisers couldn't be trusted"
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.
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.