I'm working in some legacy VB code (.aspx page) and all over the place I see conditionals of this format:
If (someVar And {integer_x}) = {integer_x} Then
And I've seen all kinds of integers, but they all seem to be powers of 2 (8, 64, 256, 16384, etc.).
What does this code do?
This is a bitwise check. This article says it all.
(But link-only answers are frowned upon, so...)
When you do bitwise operations, you look for a bit that's "on", or has the value 1. If you look for someVar And 8, that's saying "does someVar have its 4th bit on from the right at the on position".
8 translates in binary as 0001000. If someVar has a 1 in that position, the logical operator And will return 0001000, or 8. And then you check for equality. Note that someVar can still have other bits on. It could be worth 9 (0001001), and that would still mean the condition is true.
Now, unless this is for an interface with an electronic system or parsing raw data, I'd say that's a really outdated way of doing what Enum with the Flags attribute can do.
Let's fast-forward to today:
<Flags()> _
Enum PizzaToppings
Sauce = 1
Pepperoni = 2
Mushrooms = 4
Peppers = 8
Bacon = 16
Ham = 32
Cheese = 64
Pineapple = 128
End Enum
'...
Dim myToppings As PizzaToppings = PizzaToppings.Sauce Or PizzaToppings.Cheese 'Use Or to combine or +
'...
If myToppings.HasFlag(PizzaToppings.Sauce) Then
addSauce()
End If
If you don't want to bother with powers, you can also do a bit shift:
1 << 0 is 2^0 is 1
1 << 1 is 2^1 is 2
1 << 2 is 2^2 is 4
1 << 3 is 2^3 is 8
Thus:
Enum PizzaToppings
Sauce = 1 << 0
Pepperoni = 1 << 1
'...
Related
This question already has answers here:
How Does Modulus Divison Work
(19 answers)
Closed 5 years ago.
I am brand new to coding and I am having a lot of trouble just getting this to work:
Declare 2 integer variables. Prompt the user for two numbers.
Store the values into variables using the Scanner object.
If the second number is a multiple of the first number, display " is a multiple of ". Otherwise display " is not a multiple of "
I have this code below then i am lost:
int number1, number2;
System.out.println("Enter a number:");
number1 = keyboard.nextInt();
System.out.println("Enter a Number:");
number2 = keyboard.nextInt();
Modulus is the remainder of dividing 2 numbers. If number2 is a multiple of number1, dividing them will have a remainder 0, otherwise not.
package test;
import java.util.Scanner;
public class MyTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number1, number2;
System.out.println("Enter a number:");
number1 = keyboard.nextInt();
System.out.println("Enter a Number:");
number2 = keyboard.nextInt();
int mod = number2 % number1;
if (mod == 0) {
System.out.println(number2 + " is a multiple of " + number1);
} else {
System.out.println(number2 + " is not a multiple of " + number1);
}
}
}
Modulus simply gives you the remainder of the division of two numbers. For eg : 4/3 gives the remainder as 1 similarly in programmatic way you can try 4%3 which two will give the same response. Added a python code snippet below :
a = int(input("Enter first no."))
b = int(input("Enter second no."))
print("Modulus operation a%b gives : ", (a % b))
print("Is ", a, " multiple of ", b)
print((a%b) == 0)
If number1 is a multiple of number2 than it will devide number2 with remainder 0,
for ex if 4 is multiple of 2 than 4%2==0, is true ,
here % is modulus operator that returns remainter of the division of two numbers :::
In your case if number1 is multiple of number2 than
Number1%number2==0 (must);
Than your program should be like this:
If(number1%number2==0)
{
System.out.println("number1 is a multiple of number 2");
}
Else
System.out.println("not a multiple");
i am lost
Suppose you are in a competition to eat chocolates and the rule is:
Eat three chocolates at the same time
If you are given:
1 chocolate, you will not eat, and 1 chocolate will be left
2 chocolates, you will not eat, and 2 chocolates will be left
3 chocolates, you eat once, and 0 chocolates will be left
4 chocolates, you eat once, and 1 chocolate will be left
5 chocolates, you eat once, and 2 chocolates will be left
6 chocolates, you eat twice, and 0 chocolates will be left
7 chocolates, you eat twice, and 1 chocolate will be left
...
100 chocolates, you eat 33 times, 1 chocolate will be left
...
1502 chocolates, you eat 500 times, 2 chocolates will be left
The number of chocolates left each time is called Modulus is Mathematics, a powerful operation in computers.
As you can tell, you will always be left with less than 3 chocolates (0 or 1 or 2) anytime.
Hence, x modulus y is always less than y in the range 0 to y-1.
In programming, the modulus operator is %.
So, if we write the way you ate chocolates using the modulus operator %, it looks like:
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
...
100 % 3 = 1
...
1502 % 3 = 2
Now tell me, are you lost?
I have never used Bitewise AND in my life. I have researched this operator but it still eludes me as to what it exactly does. So, I will ask with some code I just came across, what is the Bitwise And doing here:
CASE
WHEN (ft.Receiver_Status & 2) = 2 THEN '3D'
WHEN (ft.Receiver_Status & 1) = 1 THEN '2D'
WHEN (ft.Receiver_Status & 32) = 32 THEN 'Invalid' -- AR 220312
ELSE 'None'
Is it enforcing the same datatype, such as smallint converts to int before comparing the value of Receiver_Status?
ft.Receiver_Status & 1: 1 is 20, so it is pulling out the value of the bit at position 0.
ft.Receiver_Status & 2: 2 is 21, so it is pulling out the value of the bit at position 1.
ft.Receiver_Status & 32: 32 is 25, so it is pulling out the value of the bit at position 5.
Note that, for example, the = 32 in (ft.Receiver_Status & 32) = 32 is actually redundant. This could instead be (ft.Receiver_Status & 32) != 0 because all you're interested in is whether that bit is a 0 or a 1.
The bitwise AND checks to see whether a particular bit is set. It appears ft.Receiver_Status is an integer which stores various flags in different bits.
1 in binary is 00001 so ft.Receiver_Status & 1 is checking to see if the first bit is set.
2 in binary is 00020 so ft.Receiver_Status & 1 is checking to see if the second bit is set.
32 in binary is 10000 so ft.Receiver_Status & 32 is checking to see if the fifth bit is set.
To see precisely how this works, the result of the AND operation will be the bit at position n will be 1 f and only if the bit at position n in both the first and the second number is 1. Consider the following binary numbers:
011010001 (209)
000010000 ( 32)
---------------
000010000 ( 32)
And alternatively,
011001001 (201)
000010000 ( 32)
---------------
000000000 ( 0)
(something & constant) == constant (where constant is a power of two) is a way of ensuring that the bit defined in constant is set. Consider your first case. All of the bits in 2 aren't set except for the second bit, so we know the rest will be zero. If the second bit is not set in Receiver_Status then the result will be zero, if it is set, that bit will be one and the result will be two, the same as the bit mask.
It could also be written as (ft.Receiver_Status & 2) > 0 to avoid repeating the bit mask in each case.
You should read about bit flags. That's the way to check, if particular bit within a bigger data type (e.g. byte) is set to 1 or not.
Example:
Consider having a bite with following bits content: 00110101. You'd like to check the fifth position. You need to change all other bits to 0 and check, if that one is 1 or 0. To do that, perform bitewise AND with 2^4:
00110101
00010000 &
--------
00010000
To give a concrete example with all these other great answers, if Receiver_Flags were 3, the 1 and 2 bits are on. Likewise, if it were 34, the 2 and 32 bits are on.
A lot of times an enum is used to set these fields. Consider this enum:
public enum Flags
{
ThreeD = 1,
TwoD = 2,
Invalid = 3
}
You might set the value like this:
Receiver_Flags = Flags.ThreeD | Flags.TwoD
and the value would be 3. In that case the 1 and 2 bits would be on.
This is very similar to Enum.HasFlag. Here's one way to implement that for a Test enum:
static bool HasFlag(Test flags, Test flag)
{
return (flags & flag) != 0;
}
Basically, (ft.Receiver_Status & 32) = 32 checks if the fifth bit is 1 or 0.
I'm working on the development of the eclipse plugin based on CDT.
The plugin parses the C++ code and generates another C++ code based on the data from parsed code.
Suppose the original code is
enum SOMEENUM
{
ONE = 1 << 1 // Bit 2 2
,TWO = 1 << 2 // Bit 3 4
,THREE = 1 << 3 // Bit 4 8
,FOUR = 1 << 4 // Bit 5 16
}
CDT recognizes the 1 << 1, 1 << 2, etc as IASTBinaryExpression.
Question : Does anybody know how is it possible to evaluate the value of each binary expression by means of CDT ?
Otherwise the only option remain the calculation by manual parsing of all operands.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi, I am new to Visual Basic, I have a project where I need to be able to manipulate individual bits in a value.
I need to be able to switch these bits between 1 and 0 and combine multiple occurrences of bits into one variable in my code.
Each bit will represent a single TRUE / FALSE value, so I'm not looking for how to do a single TRUE / FALSE value in one variable, but rather multiple TRUE / FALSE values in one variable.
Can someone please explain to me how I can achieve this please.
Many thanks in advance.
Does it have to be exactly one bit?
Why don't you just use the actual built in VB data type of Boolean for this.
http://msdn.microsoft.com/en-us/library/wts33hb3(v=vs.80).aspx
It's sole reason for existence is so you can define variables that have 2 states, true or false.
Dim myVar As Boolean
myVar = True
myVar = Flase
if myVar = False Then
myVar = True
End If
UPDATE (1)
After reading through the various answers and comments from the OP I now understand what it is the OP is trying to achieve.
As others have said the smallest unit one can use in any of these languages is an 8 bit byte. There is simply no order of data type with a smaller bit size than this.
However, with a bit of creative thinking and a smattering of binary operations, you can refer to the contents of that byte as individual bits.
First however you need to understand the binary number system:
ALL numbers in binary are to the power of two, from right to left.
Each column is the double of it's predecessor, so:
1 becomes 2, 2 becomes 4, 4 becomes 8 and so on
looking at this purely in a binary number your columns would be labelled thus:
128 64 32 16 8 4 2 1 (Remember it's right to left)
this gives us the following:
The bit at position 1 = 1;
The bit at position 2 = 2;
The bit at position 3 = 4;
The bit at position 4 = 8;
and so on.
Using this method on the smallest data type you have (The byte) you can pack 8 bit's into one value. That is you could use one variable to hold 8 separate values of 1 or 0
So while you cannot go any smaller than a byte, you can still reduce memory consumption by packing 8 values into 1 variable.
How do you read and write the values?
Remember the column positions? well you can use something called Bit Shifting and Bit masks.
Bit Shifting is the process of using the
<<
and
>>
operators
A shifting operation takes as a parameter the number of columns to shift.
EG:
Dim byte myByte
myByte = 1 << 4
In this case the variable 'myByte' would become equal to 16, but you would have actually set bit position 5 to a 1, if we illustrate this, it will make better sense:
mybyte = 0 = 00000000 = 0
mybyte = 1 = 00000001 = 1
mybyte = 2 = 00000010 = (1 << 1)
mybyte = 4 = 00000100 = (1 << 2)
mybyte = 8 = 00001000 = (1 << 3)
mybyte = 16 = 00010000 = (1 << 4)
the 0 through to 16 if you note is equal to the right to left column values I mentioned above.
given what Iv'e just explained then, if you wanted to set bits 5, 4 and 1 to be equal to 1 and the rest to be 0, you could simply use:
mybyte = 25(16 + 8 + 1) = 00011001 = (1 << 4) + (1 << 3) + 1
to get your bits back out, into a singleton you just bit shift the other way
retrieved bit = mybyte >> 4 = 00000001
Now there is unfortunately however one small flaw with the bit shifting method.
by shifting back and forth you are highly likely to LOOSE information from any bits you might already have set, in order to prevent this from happening, it's better to combine your bit shifting operations with bit masks and boolean operations such as 'AND' & 'OR'
To understand what these do you first need to understand simple logic principles as follows:
AND
Output is one if both the A and B inputs are 1
Illustrating this graphically
A B | Output
-------------
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1
As you can see if a bit position in our input number is a 1 and the same position in our input number B is 1, then we will keep that position in our output number, otherwise we will discard the bit and set it to a 0, take the following example:
00011001 = Bits 5,4 and 1 are set
00010000 = Our mask ONLY has bit 5 set
if we perform
00011001 AND 0010000
we will get a result of
00010000
which we can then shift down by 5
00010000 >> 5 = 00000001 = 1
so by using AND we now have a way of checking an individual bit in our byte for a value of 1:
if ((mybyte AND 16) >> 1) = 1 then
'Bit one is set
else
'Bit one is NOT set
end if
by using different masks, with the different values of 2 in the right to left columns as shown previously, we can easily extract different singular values from our byte and treat them as a simple bit value.
Setting a byte is just as easy, except you perform the operation the opposite way using an 'OR'
OR
Output is one if either the A or B inputs are 1
Illustrating this graphically
A B | Output
-------------
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1
eg:
00011001 OR 00000100 = 00011101
as you can see the bit at position 4 has been set.
To answer the fundamental question that started all this off however, you cannot use a data type in VB that has any resolution less than 1 byte, I suspect if you need absolute bit wise accuracy I'm guessing you must be writing either a compression algorithm or some kind of encryption system. :-)
01010100 01110010 01110101 01100101, is the string value of the word "TRUE"
What you want is to store the information in a boolean
Dim v As Boolean
v = True
v = False
or
If number = 84 Then ' 84 = 01010100 = T
v = True
End If
Other info
Technicaly you can't store anything in a bit, the smallest value is a char which is 8 bit. You'll need to learn how to do bitwise operation. Or use the BitArray class.
VB.NET (nor any other .NET language that I know of) has a "bit" data type. The smallest that you can use is a Byte. (Not a Char, they are two-bytes in size). So while you can read and convert a byte of value 84 into a byte with value 1 for true, and convert a byte of value 101 into a byte of value 0 for false, you are not saving any memory.
Now, if you have a small and fixed number of these flags, you CAN store several of them in one of the integer data types (in .NET the largest integer data type is 64 bits). Or if you have a large number of these flags you can use the BitArray class (which uses the same technique but backs it with an array so storage capacity is greater).
Given a NxN matrix and a (row,column) position, what is a method to select a different position in a random (or pseudo-random) order, trying to avoid collisions as much as possible?
For example: consider a 5x5 matrix and start from (1,2)
0 0 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
I'm looking for a method like
(x,y) hash (x,y);
to jump to a different position in the matrix, avoiding collisions as much as possible
(do not care how to return two different values, it doesn't matter, just think of an array).
Of course, I can simply use
row = rand()%N;
column = rand()%N;
but it's not that good to avoid collisions.
I thought I could apply twice a simple hash method for both row and column and use the results as new coordinates, but I'm not sure this is a good solution.
Any ideas?
Can you determine the order of the walk before you start iterating? If your matrices are large, this approach isn't space-efficient, but it is straightforward and collision-free. I would do something like:
Generate an array of all of the coordinates. Remove the starting position from the list.
Shuffle the list (there's sample code for a Fisher-Yates shuffle here)
Use the shuffled list for your walk order.
Edit 2 & 3: A modular approach: Given s array elements, choose a prime p of form 2+3*n, p>s. For i=1 to p, use cells (iii)%p when that value is in range 1...s-1. (For row-length r, cell #c subscripts are c%r, c/r.)
Effectively, this method uses H(i) = (iii) mod p as a hash function. The reference shows that as i ranges from 1 to p, H(i) takes on each of the values from 0 to p-1, exactly one time each.
For example, with s=25 and p=29 or 47, this uses cells in following order:
p=29: 1 8 6 9 13 24 19 4 14 17 22 18 11 7 12 3 15 10 5 16 20 23 2 21 0
p=47: 1 8 17 14 24 13 15 18 7 4 10 2 6 21 3 22 9 12 11 23 5 19 16 20 0
according to bc code like
s=25;p=29;for(i=1;i<=p;++i){t=(i^3)%p; if(t<s){print " ",t}}
The text above shows the suggestion I made in Edit 2 of my answer. The text below shows my first answer.
Edit 0: (This is the suggestion to which Seamus's comment applied): A simple method to go through a vector in a "random appearing" way is to repeatedly add d (d>1) to an index. This will access all elements if d and s are coprime (where s=vector length). Note, my example below is in terms of a vector; you could do the same thing independently on the other axis of your matrix, with a different delta for it, except a problem mentioned below would occur. Note, "coprime" means that gcd(d,s)=1. If s is variable, you'd need gcd() code.
Example: Say s is 10. gcd(s,x) is 1 for x in {1,3,7,9} and is not 1 for x in {2,4,5,6,8,10}. Suppose we choose d=7, and start with i=0. i will take on values 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, which modulo 10 is 0, 7, 4, 1, 8, 5, 2, 9, 6, 3, 0.
Edit 1 & 3: Unfortunately this will have a problem in the two-axis case; for example, if you use d=7 for x axis, and e=3 for y-axis, while the first 21 hits will be distinct, it will then continue repeating the same 21 hits. To address this, treat the whole matrix as a vector, use d with gcd(d,s)=1, and convert cell numbers to subscripts as above.
If you just want to iterate through the matrix, what is wrong with row++; if (row == N) {row = 0; column++}?
If you iterate through the row and the column independently, and each cycles back to the beginning after N steps, then the (row, column) pair will interate through only N of the N^2 cells of the matrix.
If you want to iterate through all of the cells of the matrix in pseudo-random order, you could look at questions here on random permutations.
This is a companion answer to address a question about my previous answer: How to find an appropriate prime p >= s (where s = the number of matrix elements) to use in the hash function H(i) = (i*i*i) mod p.
We need to find a prime of form 3n+2, where n is any odd integer such that 3*n+2 >= s. Note that n odd gives 3n+2 = 3(2k+1)+2 = 6k+5 where k need not be odd. In the example code below, p = 5+6*(s/6); initializes p to be a number of form 6k+5, and p += 6; maintains p in this form.
The code below shows that half-a-dozen lines of code are enough for the calculation. Timings are shown after the code, which is reasonably fast: 12 us at s=half a million, 200 us at s=half a billion, where us denotes microseconds.
// timing how long to find primes of form 2+3*n by division
// jiw 20 Sep 2011
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
double ttime(double base) {
struct timeval tod;
gettimeofday(&tod, NULL);
return tod.tv_sec + tod.tv_usec/1e6 - base;
}
int main(int argc, char *argv[]) {
int d, s, p, par=0;
double t0=ttime(0);
++par; s=5000; if (argc > par) s = atoi(argv[par]);
p = 5+6*(s/6);
while (1) {
for (d=3; d*d<p; d+=2)
if (p%d==0) break;
if (d*d >= p) break;
p += 6;
}
printf ("p = %d after %.6f seconds\n", p, ttime(t0));
return 0;
}
Timing results on 2.5GHz Athlon 5200+:
qili ~/px > for i in 0 00 000 0000 00000 000000; do ./divide-timing 500$i; done
p = 5003 after 0.000008 seconds
p = 50021 after 0.000010 seconds
p = 500009 after 0.000012 seconds
p = 5000081 after 0.000031 seconds
p = 50000021 after 0.000072 seconds
p = 500000003 after 0.000200 seconds
qili ~/px > factor 5003 50021 500009 5000081 50000021 500000003
5003: 5003
50021: 50021
500009: 500009
5000081: 5000081
50000021: 50000021
500000003: 500000003
Update 1 Of course, timing is not determinate (ie, can vary substantially depending on the value of s, other processes on machine, etc); for example:
qili ~/px > time for i in 000 004 010 058 070 094 100 118 184; do ./divide-timing 500000$i; done
p = 500000003 after 0.000201 seconds
p = 500000009 after 0.000201 seconds
p = 500000057 after 0.000235 seconds
p = 500000069 after 0.000394 seconds
p = 500000093 after 0.000200 seconds
p = 500000099 after 0.000201 seconds
p = 500000117 after 0.000201 seconds
p = 500000183 after 0.000211 seconds
p = 500000201 after 0.000223 seconds
real 0m0.011s
user 0m0.002s
sys 0m0.004s
Consider using a double hash function to get a better distribution inside the matrix,
but given that you cannot avoid colisions, what I suggest is to use an array of sentinels
and mark the positions you visit, this way you are sure you get to visit a cell once.