during some code conversion from another persons VB.net project to C#, i have come across the following code:
Public Sub New(ByVal lbytModuleAddress As Byte, ByVal lbytRelayStateMask As Byte)
Dim lintCounter As Integer
mbytModuleAddress = lbytModuleAddress
For lintCounter = 0 To 7
If lbytRelayStateMask And (2 ^ lintCounter) Then
mblnRelayState(lintCounter) = True
Else
mblnRelayState(lintCounter) = False
End If
Next
End Sub
Now m trying to convert this to C#, but im a little confused as to exactly the meaning of this line:
If lbytRelayStateMask And (2 ^ lintCounter) Then
Could someone please enlighten me? It appears there something going on behind the scenes (that ill have to examine further) however before i do i would just like to clarify the result of this if statement.
Am i correct in saying if either one of the sub-expressions equals zero then its false, otherwise its true? Sorry, im not too up to speed on VB.net.
lbytRelayStateMask And (2 ^ lintCounter) results in BIT number lintCounter, which is on or off. a bit is a boolean value. AND is a bit operation, not the AND in an IF
th author might have written too:
mblnRelayState(lintCounter) = (lbytRelayStateMask And (2 ^ lintCounter))
Yes, I believe you are correct in your analysis.
Related
Hi so im making a program in VB.Net which will hopefully output the MD5 hash of a string without using System.Security.Cryptography (not the smartest but i fancied a challenge) using the implementation from here: https://www.rfc-editor.org/rfc/rfc1321
Anyway im getting an Arithmetic overflow when i run my code. Up until this point it has been running rather smoothly with the inputted string being converted to binary, padded correctly etc.
However when i get to stage 4 where i have to process the message block it goes a little strange. Specifically on this function where it returns an Arithmetic overflow on the line labelled:
Function R1(ByRef a As ULong, ByRef b As Integer, ByRef c As Integer, ByRef d As Integer, ByRef splitmessagepart As String, ByRef S As Integer, ByRef i As Integer, ByRef T() As Long)
'the line below returns the arithmetic overflow
a = b + ((a + (f(b, c, d)) + splitmessagepart + T(i)) << S)
Return a
End Function
This is function F:
Function f(ByRef X As String, ByRef Y As String, ByRef Z As String)
Dim endresult As String
endresult = (X And Y) Or (Not X And Z)
Return endresult
End Function
And then this is the line which calls the function R1:
splitmessagepart = splitmessage(0)
a = R1(a, b, c, d, splitmessagepart, 7, 1, T)
Through some debugging i have found that my splitmessagepart variable isnt correctly translated from Binary to decimal in another function but even if i change it so that it is the correct decimal version i still get the overflow. Im assuming this happens on the other 3 functions also which do something similar to this however the program encounters an error on the first line.
I was wondering if i could have a little help figuring out why this is happening? If theres any code needed that i havent put in please ask i really want to get this to work!
Thanks
You should split the calculation into its parts and check precisely with the watch which operator throws the exception.
More importantly, it looks like you have set the option strict off. This not a good practice unless you absolutely have to. You define the parameters of the function f as string, but you pass Integers to it, so they will implicitly converted to strings. Inside f you use and and or which will again implicitly convert your parameters because these operators are not defined on strings. Also you have not defined the type of the output of the function.
More over you have defined splitmessagepart as string and you try to use + between strings and integers. Are you aware what the result will be.
I advise you to turn the option strict on and check on all these implicit conversions, they are probably not what you expect.
FYI, the doc states that a word is a 32-bit object, so an integer. I doubt there should be a string anywhere in the algorithm.
Ok so I was in college and I was talking to my teacher and he said my code isn't good practice. I'm a bit confused as to why so here's the situation. We basically created a for loop however he declared his for loop counter outside of the loop because it's considered good practice (to him) even though we never used the variable later on in the code so to me it looks like a waste of memory. We did more to the code then just use a message box but the idea was to get each character from a string and do something with it. He also used the Mid() function to retrieve the character in the string while I called the variable with the index. Here's an example of how he would write his code:
Dim i As Integer = 0
Dim justastring As String = "test"
For i = 1 To justastring.Length Then
MsgBox( Mid( justastring, i, 1 ) )
End For
And here's an example of how I would write my code:
Dim justastring As String = "test"
For i = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
Would anyone be able to provide the advantages and disadvantages of each method and why and whether or not I should continue how I am?
Another approach would be, to just use a For Each on the string.
Like this no index variable is needed.
Dim justastring As String = "test"
For Each c As Char In justastring
MsgBox(c)
Next
I would suggest doing it your way, because you could have variables hanging around consuming(albeit a small amount) of memory, but more importantly, It is better practice to define objects with as little scope as possible. In your teacher's code, the variable i is still accessible when the loop is finished. There are occasions when this is desirable, but normally, if you're only using a variable in a limited amount of code, then you should only declare it within the smallest block that it is needed.
As for your question about the Mid function, individual characters as you know can be access simply by treating the string as an array of characters. After some basic benchmarking, using the Mid function takes a lot longer to process than just accessing the character by the index value. In relatively simple bits of code, this doesn't make much difference, but if you're doing it millions of times in a loop, it makes a huge difference.
There are other factors to consider. Such as code readability and modification of the code, but there are plenty of websites dealing with that sort of thing.
Finally I would suggest changing some compiler options in your visual studio
Option Strict to On
Option Infer to Off
Option Explicit to On
It means writing more code, but the code is safer and you'll make less mistakes. Have a look here for an explanation
In your code, it would mean that you have to write
Dim justastring As String = "test"
For i As Integer = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
This way, you know that i is definitely an integer. Consider the following ..
Dim i
Have you any idea what type it is? Me neither.
The compiler doesn't know what so it defines it as an object type which could hold anything. a string, an integer, a list..
Consider this code.
Dim i
Dim x
x = "ab"
For i = x To endcount - 1
t = Mid(s, 999)
Next
The compiler will compile it, but when it is executed you'll get an SystemArgumenException. In this case it's easy to see what is wrong, but often it isn't. And numbers in strings can be a whole new can of worms.
Hope this helps.
Is it possible to convert, say, a textbox input to working code?
For example, user types 'if x<10 then y=2 else y=5' into textbox1, it gets used directly as code something like ...
dim x as integer = 5
dim y as integer = 0
include processed textbox1.text
resultbox.text = (y*20).tostring
It's not important why this would be needed - just whether there is any straight-forward method that parses a string to code.
Many thanks.
Maybe this is what you are looking for:
http://www.codeproject.com/Articles/12852/Compile-and-Run-VB-NET-Code-using-the-CodeDom
yes you can do this using the VBCodeProvider class. Although the amount of code required is quite significant:
http://www.codeproject.com/Articles/5472/Compiling-NET-code-on-the-fly
What's the return value when I do an assignment?
For example, can I do this? (i.e. the assignment returns the value being assigned)
Dim a As Integer = 1
Dim b As Integer = 2
a = b = 3
The question came up when I wrote this code today:
Dim updates = GetUpdates()
While updates.Count > 0
Foo.ApplyUpdates(updates)
updates = GetUpdates()
End While
I kind of wish I could have written it this way...
While (updates = GetUpdates).Count > 0
Foo.ApplyUpdates(updates)
End While
I know it's not as clean... (and I totally never declared updates) but it got me curious about how assignments work in .NET... is it a function with a return value? If so... what does it return?
Edit
I gave the first chunk of code a try. It looks like the compiler interprets it as assigning the result of comparing b and 3 to a... which is a compiler error of course.
And for the second code chunk, I get that the operator = is not defined for what ever type updates is... i.e. it thinks it's a comparison, not an assignment.
So to add to my question, why does it work this way? Is it just because vb.net overloads the symbol = with two meanings (assignment and comparison)?
about how assignment working in .NET.
This is actually about how assignment works in VB, not in .NET.
This does not work in VB.Net. The = Operator in VB.Net merely "assigns the value on its right to the variable or property on its left."
What's the return value when I do an assignment?
As seen in the above statement, the assignment operator does not return a value in VB.Net.
Note that this differs from other .NET languages. For example, in C#, the assignment = Operator does what you're describing, and "stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result."
Dim a As Integer
Dim b As Integer
a = b = 3
Note that, with Option Strict specified, this will actually be an error: "Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'."
This is because VB.Net sees this as two operations - it's basically trying to do:
Dim a As Integer
Dim b As Integer
Dim temp as Boolean
temp = (b = 3)
a = temp
So to add to my question, why does it work this way? Is it just because vb.net overloads the symbol = with two meanings (assignment and comparison)?
Well, it's how the language was designed. I suspect that you are correct, though, and since the same operator (=) is used as an assignment and a comparison is why VB was made this way. However, the original VB language was this way, and to keep the syntax for VB.Net the same (or as close as possible), I suspect this behavior was carried forward.
In Visual Basic a = b = 3 translates to something somewhat unexpected. Since VB doesn't have the == operator and instead uses = for both assignments and equality comparision, the above expression comes down to the following:
If b = 3 Then
a = True
Else
a = False
End If
I have a value in variable, say it is dim a as integer = 145.98
I tried to take the Left(a,2)
but it returned an error instead of returning 14
I also tried left(a.Tostring,2)
but error is the same.
Please help me solve it.
Thanks
Furqan
First off, you say that you’re using an integer but the number is actually a floating-point number, not an integer.
Secondly, the action “take the left of a number” isn’t a meaningful operation. Left is a substring operation, it’s only defined on strings.
You can turn the number into a string and then extract a substring of the decimal representation. This should work. What’s the error?
Finally, some general advice:
Put Option Strict On at the very top of ever vb file, or better yet, make this option the default in your settings. Otherwise, you’ve got a veritable hullaballoo waiting to happen because VB is very … “lenient” when it comes to questionable or downright incorrect code. This option fixes this and will flag a lot more errors. For example, the compiler would (rightfully) have complained about your assignment,
Dim a As Integer = 145.98
because as I said, you’re trying to assign a floating-point number to an integer.
First of all, 145.98 is not an integer. 145 is an integer. You might want to try Double. Second, you can only take the left of a string. You were on the right track when you added ToString, but you forgot the ()s at the end.
Dim a as Integer = 145
Dim b as Double = 145.98
Then you can do this:
Left(a.ToString(), 2)
Left(b.ToString(), 2)
Try Left(a.ToString(), 2) instead.
If your "integer" is a string, try this:
Dim a As String = "145.98"
Dim b As Int32 = 0
Int32.TryParse(a.Substring(0, 2), b)
As Konrad has said with option strict this would not compile. If you don't have it on it will perform a conversion and store only the integer part. At this point you can call tostring and then performe any operation on it as a string you would like.
With option strict
Option Strict On
Module Module1
Sub Main()
Dim I As Integer = CType(142.3, Integer)
Dim s As String = I.ToString
Console.WriteLine(Left(s, 2))
End Sub
End Module
With out optiion strict
Module Module1
Sub Main()
Dim I As Integer = 142.3
Dim s As String = I
Console.WriteLine(Left(s, 2))
End Sub
End Module
As you can see from the two example option strict will attempt to perform many conversions for you but does so at the risk of unexpected results.