Checking bit state of lpt port binary - c#

I've part of code which is checking input pins of lpt port, but using decimal values:
while (PortAccess.Input(889) == 120)
How to use this instruction with binary values?
for example while bit 3 of 00100100 is 0 then do something.

See Convert.ToInt32(string value, int fromBase)
while((value & Convert.ToInt32("00000100", 2)) == 0)
Or since we know the third bit is for (2^2)
while((value & 0x0004) == 0)
is also a clear enough piece of code, I guess.

Ok, so i've done this, because tafa solution wasn't working and i couldn't make it work:
var PortValue = Convert.ToString(PortAccess.Input(889), 2).PadLeft(8, '0');
PortV.Text = PortValue;
while (PortV.Text[3].ToString() == "1")
{
//some code
}
It's probably not good solution, but it's working ;)

Related

Principal variation in chess engine - How could I rewrite this C code into C#?

I need help rewriting this code (the blue parts in the link) to C#. I have little experience with programming in C or C++, so I am not sure how exactly should I interpret the tagMove structure and -> operator in C#.
http://web.archive.org/web/20040427013839/brucemo.com/compchess/programming/pv.htm
If somebody doesn't want to click the link, I also posted the code here:
typedef struct LINE
{
int cmove; // Number of moves in the line.
MOVE argmove[moveMAX]; // The line.
}
LINE;
int AlphaBeta(int depth, int alpha, int beta, LINE * pline)
{
LINE line;
if (depth == 0) {
pline->cmove = 0;
return Evaluate();
}
GenerateLegalMoves();
while (MovesLeft()) {
MakeNextMove();
val = -AlphaBeta(depth - 1, -beta, -alpha, &line);
UnmakeMove();
if (val >= beta) return beta;
if (val > alpha) {
alpha = val;
pline->argmove[0] = ThisMove();
memcpy(pline->argmove + 1, line.argmove, line.cmove * sizeof(MOVE));
pline->cmove = line.cmove + 1;
}
}
return alpha;
}
You are mentioning that you don't know what the "->" operator does in C#, there it is just a "." if something contains a property you access it with a simple dot, lets say that we have an object country with some values, to access each one:
Country.Capital
Country.President
etc...
now, the problem with your question is that it is extremely basic, and there is nothing wrong with that, we all started somewhere, but start working in a chess engine at your level does feels odd, not sure if someone is going to take the time to rewrite that for you , but you will 100% encounter other problems along the way that you will not know how to solve, my advice would be to leave this on hold, focus on the basics and then come back and smash that code with your brand new knowledge

Protecting against Divide by Zero

I'm running into a problem that I think in my mind should work, but keep returning the same Divide by Zero error.
Here is the code I am using that I think should protect against it:
GoalBarValue = Convert.ToInt32(((decimal)CompletedToday /
((decimal)CompletedYesterday) == 0 ? (decimal?)null : (decimal)CompletedYesterday)
* 100); // Divide by zero protection
CompletedToday comes back as 0
CompletedYesterday comes back as 0
Which is perfectly fine and as I expect it should.
The specific error that is being returned is Attempted to divide by zero.
Is something wrong with the way I am trying to protect against it?
"Is something wrong with the way I am trying to protect against it?"
Yes actually, you are dividing by zero! The only way that 0 can be the outcome of your calculation is when CompletedToday is 0. In the other case you divide by 0 and get the nice exception. Why don't you just check whether the divisor is 0 and if not perform the calculation else give it a null :
GoalBarValue = Convert.ToInt32((decimal)CompletedYesterday) == 0 ?
(decimal?)null : (decimal)CompletedYesterday * 100;
Imagine you would check whether you hit your head against a wall by hitting your head against the wall..... it wouldn't be advisable.
EDIT:
If you want 2 assignments of different variables (as you wrote in your comment) then the ? operator is not of much use to you. It allows only 1.
I would suggest to stick to the old fashion way. If you really want the 2 assignments in one line:
if((decimal)CompletedYesterday) == 0)
GoalBarValue = CompletedYesterday = null;
else GoalBarValue = // what ever you want to calculate...
Is this what you want?
if (Convert.ToDecimal(CompletedYesterday) == 0)
{
goalBarValue = null;
}
else
{
goalBarValue = Convert.ToInt32(Convert.ToDecimal(CompletedToday)/Convert.ToDecimal(CompletedYesterday)) * 100;
}
one line version of above code
goalBarValue = Convert.ToDecimal(CompletedYesterday) == 0 ? null : Convert.ToInt32(Convert.ToDecimal(CompletedToday)/Convert.ToDecimal(CompletedYesterday)) * 100;

How to efficiently check if a binary schema is a sub-schema of another binary schema

I have a string consisting of 0, 1 and * (wildcard character) and this is called a binary schema, e.g. 0*10*.
Suppose I have a list of schemas e.g. [11010, 0010*, 0*11*, 1*100], only 0010* is sub-schema of 0*10*.
All schemas being compared are guaranteed to be of same length, though can be set initially in the program.
Edit:
So far, here's the step solution I can think of:
find wildcard indices in both schema and compare if one is superset to the other.
if true, then remove all characters in superset indices to both schema string.
return true if both trimmed schema is of same string.
Is there a more efficient way to do this? What I mean efficient is in terms of execution speed / as few iterations as possible because the checker will be invoked very frequently.
If I understand the question correctly this should do what you want and it performs as little work as possible assuming mismatching positions are unbiased. It might however be faster not to use LINQ. If you need the resulting list only once you can probably get away without turning the result into a list.
var s = "0*10*";
var sscs = new[] { "11010", "0010*", "0*11*", "1*100" };
var sss = sscs.Where(ssc => s.Zip(ssc, (a, b) => (a == b) || (a == '*')).All(_ => _)).ToList();
Every subschema candidate is compared symbol by symbol with the specified schema. If all symbols match or the schema has a wildcard in case of an mismatch the subschema candidate is a subschema. The comparison is aborted immediately if there is a mismatch and schema has no wildcard.
I heavily abbreviated the variable names to make it (almost) fit.
s schema
sscs subschema candidates
ssc subschema candidate
sss subschemas
a symbol in schema
b symbol in subschema candidate
Not exactly sure what you are asking, but I assume that you have a starting list of schemas that you are working off of, and that list is unique (no subsets, etc).
Define a simple IsSubsetOf() function, and then call that as part of a Linq 'any' call, or you can do it in a for-loop:
var startingSchemas = new [] { "100**101", "110*101*", "1111*000" };
startingSchemas.Any(x => IsSubsetOf(x, "11****11")); // false
startingSchemas.Any(x => IsSubsetOf(x, "11011010")); // true
public bool IsSubsetOf(string main, string sub)
{
for (var i = 0; i < main.Length; i++)
{
if (main[i] == '*') continue; // main is '*', so anything is ok
if (main[i] == sub[i]) continue; // equal is ok, both 1/0/*
return false; // if not equal, sub[i] could be *, or the opposite of main[i]
}
return true;
}
One issue that I think you might need to clarify is what you want to do when you find something that is NOT a subset, but when combined with another schema then it is.
1*1 => 101 or 111
0*1 => 001 or 011 (not a subset of 1*)
But these two combined = the **1 schema or {001, 011, 101, 111}
Do you want to take a string list and then reduce it to the minimal set of schemas that will still match the same inputs? IsSubset(x,y) = false, but IsSubset(y,x) = true
Addition:
Making the starting data unique is pretty easy, if it isn't already:
var uniqueSchemas = startingSchemas.Distinct().ToList();
uniqueSchemas.RemoveAll(x => uniqueSchemas.Any(y => y != x && IsSubsetOf(y, x)));
Compiled (release, no pdb, optimize):
for (int index = 0; index < main.Length; ++index)
{
if ((int) main[index] != 42 && (int) main[index] != (int) sub[index])
return false;
}
Performance
Very crude performance check. Run in parallels VM on an i7/4gb 1 core allocated to vm, other processes running, etc.
200 schemas (randomly generated, 800 length)
1 test string (800 length, randomly generated the same way)
1 millions runs each
Output: (all runs were +/- 500ms at the outside, usually in unison)
// unsafe = new 'public static void unsafe IsSubsetOf' function using pointers
// safe = standard method
Any() warmup : elapsed = 11965 (.0120 ms)
Any() safe : elapsed = 11300 (.0113 ms)
Any() unsafe : elapsed = 10754 (.0108 ms)
for() safe : elapsed = 11480 (.0115 ms)
for() unsafe : elapsed = 7964 (.008 ms)
So, that what I get from this. If there is a clever data structure for this, i've no clue.
Unsafe Version
This isn't guaranteed to be 100% correct. I don't normally do this, and I don't know if the discrepancy I saw was because of the test harness or the code. Also, disclaimer, it's been a good 6 years since I wrote a tiny bit of unsafe code. But I don't pump .net for performance this way, there is usually a bigger bottleneck... If you do use unsafe code, my only advice would be to NOT modify anything. If you just read you should be pretty safe. Check all your bounds!
private unsafe static bool IsSubsetOfUnsafe(String main, String sub)
{
if (main == null && sub == null) return true; // is this what you want? decide
if (main == null || sub == null) return false; // this too? maybe if null then say "true" and discard?
if (main.Length != sub.Length) return false;
fixed (char* m = main)
fixed (char* s = sub)
{
var m1 = m;
var s1 = s;
int len = main.Length;
for (int i = 0; i < len; ++i)
{
if ((int)m1 != 42 && m1 != s1) return false;
m1++;
s1++;
}
return true;
}
}
Unfortunately I still don't fully understand what you are doing but I will present my idea anyway, maybe it is useful.
The central idea is to replace your string representation with a more compact bit representation - your string 1*10 for example gets turned into 11001110 or 0xCE. Because one symbol takes up 2 bits you can pack 32 symbols into one UInt64, longer strings become arrays of UInt64s.
0 => 10
1 => 11
* => 00
01 => unused
Now you can find subschemas with the following LINQ expression
var sss = sscs.Where(ssc => s.Zip(ssc, (a, b) => (a ^ b) & ((a & 0xAAAAAAAAAAAAAAAA) | ((a & 0xAAAAAAAAAAAAAAAA) >> 1))).All(x => x == 0)).ToList();
that is structure like my previous answer to make the comparison more meaningful. The obvious advantage is that it processes 32 symbols in parallel and indeed it is 30 times faster than my previous answer. But I am actually a bit disappointed because I hopped for maybe a 100 times speedup because the compacter representation also means less memory traffic but maybe the overhead from using LINQ is the actual bottleneck. So I turned it into plain for loops and this made it 130 times faster than the LINQ string version. But this is only really useful if it can be deeply integrated into your application because the conversion between the string representation and this representation is quite expensive.

toString() of int e = 0000007 omits all zeros. How can I preserve them?

I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.

string.Format() parameters

How many parameters can you pass to a string.Format() method?
There must be some sort of theoretical or enforced limit on it. Is it based on the limits of the params[] type or the memory usage of the app that is using it or something else entirely?
OK, I emerge from hiding... I used the following program to verify what was going on and while Marc pointed out that a string like this "{0}{1}{2}...{2147483647}" would succeed the memory limit of 2 GiB before the argument list, my findings did't match yours. Thus the hard limit, of the number of parameters you can put in a string.Format method call has to be 107713904.
int i = 0;
long sum = 0;
while (sum < int.MaxValue)
{
var s = sizeof(char) * ("{" + i + "}").Length;
sum += s; // pseudo append
++i;
}
Console.WriteLine(i);
Console.ReadLine();
Love the discussion people!
Not as far as I know...
well, the theoretical limit would be the int32 limit for the array, but you'd hit the string length limit long before that, I guess...
Just don't go mad with it ;-p It may be better to write lots of small fragments to (for example) a file or response, than one huge hit.
edit - it looked like there was a limit in the IL (0xf4240), but apparently this isn't quite as it appears; I can make it get quite large (2^24) before I simply run out of system memory...
Update; it seems to me that the bounding point is the format string... those {1000001}{1000002} add up... a quick bit of math (below) shows that the maximum useful number of arguments we can use is 206,449,129:
long remaining = 2147483647;// max theoretical format arg length
long count = 10; // i.e. {0}-{9}
long len = 1;
int total = 0;
while (remaining >= 0) {
for(int i = 0 ; i < count && remaining >= 0; i++) {
total++;
remaining -= len + 2; // allow for {}
}
count *= 10;
len++;
}
Console.WriteLine(total - 1);
Expanding on Marc's detailed answer.
The only other limitation that is important is for the debugger. Once you pass a certain number of parameters directly to a function, the debugger becomes less functional in that method. I believe the limit is 64 parameters.
Note: This does not mean an array with 64 members, but 64 parameters passed directly to the function.
You might laugh and say "who would do this?" which is certainly a valid question. Yet LINQ makes this a lot easier than you think. Under the hood in LINQ the compiler generates a lot of code. It's possible that for a large generate SQL query where more than 64 fields are selected that you would hit this issue. Because the compiler under the hood would need to pass all of the fields to the constructor of an anonymous type.
Still a corner case.
Considering that both the limit of the Array class and the String class are the upper limit of Int32 (documented at 2,147,483,647 here: Int32 Structure), it is reasonable to believe that this value is the limit of the number string of format parameters.
Update Upon checking reflector, John is right. String.Format, using the Red Gate Reflector, shows the ff:
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}
The format.Length + (args.Length * 8) part of the code is enough to kill most of that number. Ergo, '2,147,483,647 = x + 8x' leaves us with x = 238,609,294 (theoretical).
It's far less than that of course; as the guys in the comments mentioned the string hitting the string length limit earlier is quite likely.
Maybe someone should just code this into a machine problem! :P

Categories

Resources