Bit operator AND does not return a value [closed] - vb.net

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So I have this code:
Dim a As Byte = (1 << 1)
Dim b As Byte = (1 << 2)
Dim c As Byte = (1 << 3)
Dim res As Byte
res = a And b And c
The result (res) is 0. Why? I just want to manipulate the bits in this, but the return value is always 0. All tutorials show me, that this should work. Some do something like Dim a As Byte = 2, but shouldn't it be unimportant how to set the value of a byte?
My debugger also shows me that the bytes a, b and c are set correctly. What am I doing wrong?
Edit:
It was a huge mistake on my side. I knew that I needed to use the OR operator but didnt. I just had a big brain lag. Excuse me for being this impatient and not thinking this over properly. I will leave this question here so maybe someone sees that this is his/her problem, too.
Again, please excuse me.

Because the result of 2 and 4 and 8 is 0. None of those numbers have any binary columnar digits in common:
2 is 0010
4 is 0100
8 is 1000
AND works down the column and only records a 1 in the result if all the values in the column are 1:
3 AND 5
3 is 0011
5 is 0101
result is 0001
^ only this column has all 1s in it.
The result of 3 And 5 is 1
All tutorials show me, that this should work
Show us those tutorials, so we can better understand what is going wrong in the process of the_tutorial --> your_brain - one or the other parts of that operation has an error! :)

I suspect that you don't actually understand what the bitwise And operator does. Zero is exactly what you should expect from that code. You should have told us this in the first place but what do you expect and why? I suspect that you actually want the Or operator rather than And. Regardless, you should read up and learn what those bitwise operators actually do. It might also help to look at those values in a more obvious way:
Module Module1
Sub Main()
Dim a As Byte = (1 << 1)
Dim b As Byte = (1 << 2)
Dim c As Byte = (1 << 3)
Display(a)
Display(b)
Display(c)
Display(a And b And c)
Display(a Or b Or c)
Console.ReadLine()
End Sub
Sub Display(b As Byte)
Console.WriteLine(Convert.ToString(b, 2).PadLeft(32, "0"c))
End Sub
End Module
Output:
00000000000000000000000000000010
00000000000000000000000000000100
00000000000000000000000000001000
00000000000000000000000000000000
00000000000000000000000000001110

Related

Given no modulus or if even/odd function, how would one check for an odd or even number?

I have recently sat a computing exam in university in which we were never taught beforehand about the modulus function or any other check for odd/even function and we have no access to external documentation except our previous lecture notes. Is it possible to do this without these and how?
Bitwise AND (&)
Extract the last bit of the number using the bitwise AND operator. If the last bit is 1, then it's odd, else it's even. This is the simplest and most efficient way of testing it. Examples in some languages:
C / C++ / C#
bool is_even(int value) {
return (value & 1) == 0;
}
Java
public static boolean is_even(int value) {
return (value & 1) == 0;
}
Python
def is_even(value):
return (value & 1) == 0
I assume this is only for integer numbers as the concept of odd/even eludes me for floating point values.
For these integer numbers, the check of the Least Significant Bit (LSB) as proposed by Rotem is the most straightforward method, but there are many other ways to accomplish that.
For example, you could use the integer division operation as a test. This is one of the most basic operation which is implemented in virtually every platform. The result of an integer division is always another integer. For example:
>> x = int64( 13 ) ;
>> x / 2
ans =
7
Here I cast the value 13 as a int64 to make sure MATLAB treats the number as an integer instead of double data type.
Also here the result is actually rounded towards infinity to the next integral value. This is MATLAB specific implementation, other platform might round down but it does not matter for us as the only behavior we look for is the rounding, whichever way it goes. The rounding allow us to define the following behavior:
If a number is even: Dividing it by 2 will produce an exact result, such that if we multiply this result by 2, we obtain the original number.
If a number is odd: Dividing it by 2 will result in a rounded result, such that multiplying it by 2 will yield a different number than the original input.
Now you have the logic worked out, the code is pretty straightforward:
%% sample input
x = int64(42) ;
y = int64(43) ;
%% define the checking function
% uses only multiplication and division operator, no high level function
is_even = #(x) int64(x) == (int64(x)/2)*2 ;
And obvisouly, this will yield:
>> is_even(x)
ans =
1
>> is_even(y)
ans =
0
I found out from a fellow student how to solve this simplistically with maths instead of functions.
Using (-1)^n :
If n is odd then the outcome is -1
If n is even then the outcome is 1
This is some pretty out-of-the-box thinking, but it would be the only way to solve this without previous knowledge of complex functions including mod.

weird operator precedence and assignment behavior in borland turboC++

I have to use borland TurboC++ for C programming in my college.
They say our examination board recommends it. I have to use it..
The problem is that they gave this operator precedence related question:
int a=10,b=20,result;
result1 = ++a + b-- - a++ * b++ + a * ++b;
printf("result=%d",);
printf("\n a=%d",a);
printf("\n b=%d",b);
Other compilers like gcc can't perform this operation. But turbo C can and gives us:
result=32
a=12
b=21
I made mistake in my test. My teacher tried to explain what's going on. But I am not convinced. Is it some kind of weird behavior of turbo C or in older days it used to be totally fine with all compilers. If so, what are the steps to understand what is going on and how to understand.
To solve these kind of problem, turbo-c do it in manner as follows :
1) Consider the initial value of variables used.
a=10
b=20
2) Count all the pre-increment and decrements for each variable and store all post on stack separate for each variable.
for variable a
pre increment = 1 therefore change the value of a to 11
post = 1 stored to stack
for variable b
pre increment = 1 therefore change the value of b to 21
post = 2 stored to stack
3) Now replace all the pre and post with the current value of a and b
result = 11 + 21 - 11 * 21 + 11 * 21 ;
result = 11 + 21;
result = 32;
4) lastly pop the stack and perform the operation on the variable.
a = 12
b = 21
This the only way to solve this problem. You can check the procedure with any question of same kind. The result will came out same. g++ fails to solve because it probably cannot resolve the variable in the same way thus the precedence error came in picture. It might probably fail with ++ + and -- - because it cannot understand the increment or decrements operator and forms ambiguous trees.

How to test a bit in a decimal number

I have a set of decimal numbers. I need to check if a specific bit is set in each of them. If the bit is set, I need to return 1, otherwise return 0.
I am looking for a simple and fast way to do that.
Say, for example, I am checking if the third bit is set. I can do (number AND (2^2)), it will return 4 if the bit is set, otherwise it will return 0. How do I make it to return 1 instead of 4?
Thank you!
if ((number AND (2^bitnumber) <> 0) then return 1 else return 0 end if
If you can change your return type to boolean then this is more elegant
return ((number AND (2^bitnumber)) <> 0)
While the division solution is a simple one, I would think a bit-shift operation would be more efficient. You'd have to test it to be sure, though. For instance, if you are using 1 based bit indexes, you could do this:
Dim oneOrZero As Integer = (k And 2 ^ (n - 1)) >> (n - 1)
(Where k is the number and n is the bit index). Of, if you are using 0 based bit indexes, you could just do this:
Dim oneOrZero As Integer = (k And 2 ^ n) >> n
Sorry, guys, I am too slow today.
To test a bit number "n" in a decimal number "k":
(k AND 2^(n-1))/(2^(n-1))
will return 1 if the bit is set, otherwise will return 0.
=====================================================
Hi again, guys!
I compared the performance of the three proposed solutions with zero-based indexes, and here are the results:
"bit-shift solution" - 8.31 seconds
"if...then solution" - 8.44 seconds
"division solution" - 9.41 seconds
The times are average of the four consecutive runs.
Surprisingly for me, the second solution outperformed the third one.
However, after I modified the "division solution" this way:
p = 2 ^ n : oneOrZero = (k And p) / p
it started to run in 7.48 seconds.
So, this is the fastest of the proposed solutions (despite of what Keith says :-).
Thanks everybody for the help!
I really don't know if it can help anyone more than the above, but, here we go.
When I need to fast check a bit in number I compare the decimal-value of this bit directly.
I mean, if I would need to see of the 6th bit is on (32), I check its decimal value, like this:
if x and 32 = 32 then "the bit is ON"
Try for instance check 38 with 32, 4 and 2... and the other bits.
You will see only the actual bits turned on.
I hope it can help.
Yes! Simply use a bit mask. I enumerate the bits, then AND the number with the bit value. Very little math on the PC side as it uses lookup tables instead. The AND basically shuts off all the other bits except the one you are interested in. Then you check it against itself to see if it's on/off.
Enum validate
bit1 = 1
bit2 = 2
bit3 = 4
bit4 = 8
bit5 = 16
bit6 = 32
bit7 = 64
bit8 = 128
End Enum
If num And validate.bit3 = validate.bit3 Then true

Understanding the bitwise AND Operator

I have been reading about bit operators in Objective-C in Kochan's book, "Programming in Objective-C".
I am VERY confused about this part, although I have really understood most everything else presented to me thus far.
Here is a quote from the book:
The Bitwise AND Operator
Bitwise ANDing is frequently used for masking operations. That is, this operator can be used easily to set specific bits of a data item to 0. For example, the statement
w3 = w1 & 3;
assigns to w3 the value of w1 bitwise ANDed with the constant 3. This has the same ffect of setting all the bits in w, other than the rightmost two bits to 0 and preserving the rightmost two bits from w1.
As with all binary arithmetic operators in C, the binary bit operators can also be used as assignment operators by adding an equal sign. The statement
word &= 15;
therefore performs the same function as the following:
word = word & 15;
Additionally, it has the effect of setting all but the rightmost four bits of word to 0. When using constants in performing bitwise operations, it is usually more convenient to express the constants in either octal or hexadecimal notation.
OK, so that is what I'm trying to understand. Now, I'm extremely confused with pretty much this entire concept and I am just looking for a little clarification if anyone is willing to help me out on that.
When the book references "setting all the bits" now, all of the bits.. What exactly is a bit. Isn't that just a 0 or 1 in 2nd base, in other words, binary?
If so, why, in the first example, are all of the bits except the "rightmost 2" to 0? Is it 2 because it's 3 - 1, taking 3 from our constant?
Thanks!
Numbers can be expressed in binary like this:
3 = 000011
5 = 000101
10 = 001010
...etc. I'm going to assume you're familiar with binary.
Bitwise AND means to take two numbers, line them up on top of each other, and create a new number that has a 1 where both numbers have a 1 (everything else is 0).
For example:
3 => 00011
& 5 => 00101
------ -------
1 00001
Bitwise OR means to take two numbers, line them up on top of each other, and create a new number that has a 1 where either number has a 1 (everything else is 0).
For example:
3 => 00011
| 5 => 00101
------ -------
7 00111
Bitwise XOR (exclusive OR) means to take two numbers, line them up on top of each other, and create a new number that has a 1 where either number has a 1 AND the other number has a 0 (everything else is 0).
For example:
3 => 00011
^ 5 => 00101
------ -------
6 00110
Bitwise NOR (Not OR) means to take the Bitwise OR of two numbers, and then reverse everything (where there was a 0, there's now a 1, where there was a 1, there's now a 0).
Bitwise NAND (Not AND) means to take the Bitwise AND of two numbers, and then reverse everything (where there was a 0, there's now a 1, where there was a 1, there's now a 0).
Continuing: why does word &= 15 set all but the 4 rightmost bits to 0? You should be able to figure it out now...
n => abcdefghjikl
& 15 => 000000001111
------ --------------
? 00000000jikl
(0 AND a = 0, 0 AND b = 0, ... j AND 1 = j, i AND 1 = i, ...)
How is this useful? In many languages, we use things called "bitmasks". A bitmask is essentially a number that represents a whole bunch of smaller numbers combined together. We can combine numbers together using OR, and pull them apart using AND. For example:
int MagicMap = 1;
int MagicWand = 2;
int MagicHat = 4;
If I only have the map and the hat, I can express that as myInventoryBitmask = (MagicMap | MagicHat) and the result is my bitmask. If I don't have anything, then my bitmask is 0. If I want to see if I have my wand, then I can do:
int hasWand = (myInventoryBitmask & MagicWand);
if (hasWand > 0) {
printf("I have a wand\n");
} else {
printf("I don't have a wand\n");
}
Get it?
EDIT: more stuff
You'll also come across the "bitshift" operator: << and >>. This just means "shift everything left n bits" or "shift everything right n bits".
In other words:
1 << 3 = 0001 << 3 = 0001000 = 8
And:
8 >> 2 = 01000 >> 2 = 010 = 2
"Bit" is short for "binary digit". And yes, it's a 0 or 1. There are almost always 8 in a byte, and they're written kinda like decimal numbers are -- with the most significant digit on the left, and the least significant on the right.
In your example, w1 & 3 masks everything but the two least significant (rightmost) digits because 3, in binary, is 00000011. (2 + 1) The AND operation returns 0 if either bit being ANDed is 0, so everything but the last two bits are automatically 0.
w1 = ????...??ab
3 = 0000...0011
--------------------
& = 0000...00ab
0 & any bit N = 0
1 & any bit N = N
So, anything bitwise anded with 3 has all their bits except the last two set to 0. The last two bits, a and b in this case, are preserved.
#cHao & all: No! Bits are not numbers. They’re not zero or one!
Well, 0 and 1 are possible and valid interpretations. Zero and one is the typical interpretation.
But a bit is only a thing, representing a simple alternative. It says “it is” or “it is not”. It doesn’t say anything about the thing, the „it“, itself. It doesn’t tell, what thing it is.
In most cases this won’t bother you. You can take them for numbers (or parts, digits, of numbers) as you (or the combination of programming languages, cpu and other hardware, you know as being “typical”) usaly do – and maybe you’ll never have trouble with them.
But there is no principal problem if you switch the meaning of “0“ and “1”. Ok, if doing this while programming assembler, you’ll find it a bit problematic as some mnemonics will do other logic then they tell you with their names, numbers will be negated and such things.
Have a look at http://webdocs.cs.ualberta.ca/~amaral/courses/329/webslides/Topic2-DeMorganLaws/sld017.htm if you want.
Greetings

What will be the value of i in the following pseudocode?

I got this question in a programming test. Do you think this question is even correct? Look at the answer choices. (2^x means 2 raised to x)
Consider the following pseudocode.
x := 1;
i := 1;
while (x >= 1000)
begin
x := 2^x;
i := i + 1;
end;
What is the value of i at the end of the pseudocode?
a) 4
b) 5
c) 6
d) 7
e) 8
I am sure that the value of i will 1. I told the examiner of the discrepancy and he advised me the leave the question unanswered if I felt it was incorrect. What else could I have done?
1
X < 1000, so it doesn't enter the while.
Or there is an error in the Question (and X should be <= 1000 and not >=1000)
If it's <= 1000 it should be 5:
2 - 4 - 16 - 65K
2 - 3 - 4 - 5
This question tests two things:
can you read code
can you communicate / interact
Since you asked about the discrepancy, you showed 1. to be true. I'm not so sure if you passed 2, it depends too much on the situation / expectations.
I believe I would have left a note on the answer sheet stating 'none of the given'.
Not an easy situation!
As written, the answer would be 1.
Had the test on the while been reversed (i.e. x < 1000), then the series is:
At the end of each loop iteration
i = 2, x = 2
i = 3, x = 2^2 = 4
i = 4, x = 2^4 = 16
i = 5, x = 2^16 = 65,536
So i would be 5
If I where you, I would say that it is none of the above and basically say that since x is less than 1000 when the while loop starts, the value of i is never modified. I think that it is a bad thing to leave blank answers in a quiz, it is always better to write something which you think is relevant. If you think that there is a mistake, you can always state an assumption before stating your answer, so in this case you can either say that the while loop never works, or else, you explicitly state an assumption, in this case, it would be something like "Assuming that there is a mistake in the question, and that "while (x >= 1000)" should in fact be "while (x <= 1000)"...
Then, you proceed with your working.