Convert C# function to VB, char value overflow error - c#

I need the following function converted to VB.NET, but I'm not sure how to handle the statement
res = (uint)((h * 0x21) + c);
Complete function:
private static uint convert(string input)
{
uint res = 0;
foreach (int c in input)
res = (uint)((res * 0x21) + c);
return res;
}
I created the following, but I get an overflow error:
Private Shared Function convert(ByVal input As String) As UInteger
Dim res As UInteger = 0
For Each c In input
res = CUInt((res * &H21) + Asc(c)) ' also tried AscW
Next
Return res
End Function
What am I missing? Can someone explain the details?

Your code is correct. The calculation is overflowing after just a few characters since res increases exponentially with each iteration (and it’s not the conversion on the character that’s causing the overflow, it’s the unsigned integer that overflows).
C# by default allows integer operations to overflow – VB doesn’t. You can disable the overflow check in the project settings of VB, though. However I would try not to rely on this. Is there a reason this particular C# has to be ported? After all, you can effortlessly mix C# and VB libraries.

Here is a useful online converter: http://www.developerfusion.com/tools/convert/csharp-to-vb/

Related

Why integer arithmetic result showing different values in VB.NET and C#?

I have converted C# decrypt/encrypt functions to VB.NET. When I test the result in C# is showing below result but in VB.NET it throws an exception. Could you explain to me how C# showing the below result?
Below codes are tested in VS 2010 with 4.0 framework.
C# Code
class Program
{
static void Main(string[] args)
{
byte bytTen = 10;
int aa = 1527870874;
int bb = 28904;
int cc = 35756;
Console.WriteLine((bytTen + aa) * bb + cc);
Console.ReadKey();
}
}
Result: 726329420
VB.NET Code
Module Module1
Sub Main()
Dim bytTen As Byte = 10
Dim aa As Integer = 1527870874, bb As Integer = 28904, cc As Integer = 35756
Console.WriteLine((bytTen + aa) * bb + cc)
Console.ReadKey()
End Sub
End Module
Result: Arithmetic operation resulted in an overflow.
The C# code is running as unchecked code (where integer overflow is ignored).
The VB code is running in as checked, where the runtime detects an integer overflow and throws an exception.
To get the same result in VB, you need to check the project-level option "Remove integer overflow checks" on the "Advanced Compiler Settings" options via the "Compile" tab of the project options.
C# by default removes integer overflow checks (but this can also be changed on the C# project options), while VB by default has integer overflow checks.

Converting C# to VB - Private String Statement

I have been given some C# code which defined some Private String but I am not sure what it is doing honestly and need to convert into VB for my Project but wandered if someone might take a moment to explain and possible provide a conversion?
private string GetChecksum(StringBuilder buf)
{
// calculate checksum of message
uint sum = 0;
for (int i = 0; i < buf.Length; i++)
{
sum += (char)buf[i];
}
return string.Format("{0:X04}", sum);
}
The part with private string ... is the method declaration. C#'s
Accessibility ReturnType MethodName(Type paramName)
translates to
Accessibility Function MethodName(paramName As Type) As ReturnType
Private Function GetChecksum(buf As StringBuilder) As String
'calculate checksum of message
Dim sum As UInteger = 0
For i As Integer = 0 To buf.Length - 1
sum += CChar(buf(i))
Next
Return String.Format("{0:X04}", sum)
End Function
What the function does is adds up the ASCII values of each character in the string (stored in a 2-byte char without overflow checking) and return the result as a string - the 4-character hexadecimal representation of the 2-byte result.
A checksum is used to detect data errors; if two strings yield different checksums then they cannot be equal. Two strings that give the same checksum, however, are non necessarily equal, so it cannot be used to verify equality.

reading a binary unknown size file in c#

I have just switched to c# from c++. I have already done some task in c++ and the same now i have to translate in c#.
I am going through some problems.
I have to find the frequency of symbols in binary files (which is taken as sole argument, so don't know it's size/length).(these frequency will be further used to create huffman tree).
My code to do that in c++ is below :
My structure is like this:
struct Node
{
unsigned int symbol;
int freq;
struct Node * next, * left, * right;
};
Node * tree;
And how i read the file is like this :
FILE * fp;
fp = fopen(argv, "rb");
ch = fgetc(fp);
while (fread( & ch, sizeof(ch), 1, fp)) {
create_frequency(ch);
}
fclose(fp);
Could any one please help me in translating the same in c# (specially this binary file read procedure to create frequency of symbols and storing in linked list)? Thanks for the help
Edit: Tried to write the code according to what Henk Holterman explained below but still there is error and the error is :
error CS1501: No overload for method 'Open' takes '1' arguments
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
shekhar_c#.cs(22,32): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration
Compilation failed: 2 error(s), 0 warnings
And my code to do this is:
static void Main(string[] args)
{
// using provides exception-safe closing
using (var fp = System.IO.File.Open(args))
{
int b; // note: not a byte
while ((b = fp.Readbyte()) >= 0)
{
byte ch = (byte) b;
// now use the byte in 'ch'
//create_frequency(ch);
}
}
}
And the line corresponding to the two errors is :
using (var fp = System.IO.File.Open(args))
could some one please help me ? I am beginner to c#
string fileName = ...
using (var fp = System.IO.File.OpenRead(fileName)) // using provides exception-safe closing
{
int b; // note: not a byte
while ((b = fp.ReadByte()) >= 0)
{
byte ch = (byte) b;
// now use the byte in 'ch'
create_frequency(ch);
}
}

String(33, 0) in VB 6.0 and equivalent in C#

What is the meaning of UserName = String(33, 0) in VB 6.0 and what will be the equivalent in C#.
Please help I'm getting error while converting VB 6.0 code into C#.
Thanks in advance.
String in VB6 is a function that returns a string containing a repeating character string of the length specified.
String(number,character)
example:
strTest = String(5, "a")
' strTest = "aaaaa"
strTest = String(5, 97)
' strTest = "aaaaa" (97 is the ASCII code for "a")
In this case, String(33,0) will return a string containing 33 null characters.
The equivalent in C# would be
UserName = new String('\0', 33);
In VB6, that function creates a string that contains 33 characters, all of whom have zero ordinal value.
Typically you do that because you are about to pass the string to some native function which fills out the buffer. In C# the closest equivalent to that would be to create a StringBuilder instance which you would then pass to the native code in a p/invoke function call.
I think that a direct translation of that single line of code is not particularly useful. That code exists in context and I strongly suspect that the context is important.
So, whilst you could create a new C# string with 33 null characters, what would be the point of that? Since the .net string is immutable, you cannot do very much of interest with it. In your VB6 code you will surely be mutating that object, and so StringBuilder is, in my view, the most likely tool for the job.
I believe you are looking for:
UserName = new String((Char)0, 33);
Reference this for what the VB6 method did.
You can create an function that perform this action, or o can do a extenssion of the class String.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(strGen("01",3));
}
//param s is the string that you can generete and the n param is the how many times.
private static string strGen(String s, int n){
string r = string.Empty;
for (int x = 1; x <= n; x++)
r += string.Copy(s);
return r;
}
}

Conversion vb6 to c#

I am trying to convert some vb6 code to c# and I am struggling a bit.
I have looked at this page below and others similar, but am still stumped.
Why use hex?
vb6 code below:
Dim Cal As String
Cal = vbNull
For i = 1 To 8
Cal = Cal + Hex(Xor1 Xor Xor2)
Next i
This is my c# code - it still has some errors.
string Cal = null;
int Xor1 = 0;
int Xor2 = 0;
for (i = 1; i <= 8; i++)
{
Cal = Cal + Convert.Hex(Xor1 ^ Xor2);
}
The errors are:
Cal = Cal + Convert.Hex(Xor1 ^ Xor2 ^ 6);
Any advice as to why I cant get the hex to convert would be appreciated.
I suspect its my lack of understanding the .Hex on line 3 above and the "&H" on line 1/2 above.
Note: This answer was written at a point where the lines Xor1 = CDec("&H" + Mid(SN1, i, 1))
and Xor1 = Convert.ToDecimal("&H" + SN1.Substring(i, 1)); were still present in the question.
What's the &H?
In Visual Basic (old VB6 and also VB.NET), hexadecimal constants can be used by prefixing them with &H. E.g., myValue = &H20 would assign the value 32 to the variable myValue. Due to this convention, the conversion functions of VB6 also accepted this notation. For example, CInt("20") returned the integer 20, and CInt("&H20") returned the integer 32.
Your code example uses CDec to convert the value to the data type Decimal (actually, to the Decimal subtype of Variant) and then assigns the result to an integer, causing an implicit conversion. This is actually not necessary, using CInt would be correct. Apparently, the VB6 code was written by someone who did not understand that (a) the Decimal data type and (b) representing a number in decimal notation are two completely different things.
So, how do I convert between strings in hexadecimal notation and number data types in C#?
To convert a hexadecimal string into a number use
int number = Convert.ToInt32(hex, 16); // use this instead of Convert.ToDecimal
In C#, there's no need to pad the value with "&H" in the beginning. The second parameter,16, tells the conversion function that the value is in base 16 (i.e., hexadecimal).
On the other hand, to convert a number into its hex representation, use
string hex = number.ToString("X"); // use this instead of Convert.ToHex
What you are using, Convert.ToDecimal, does something completely different: It converts a value into the decimal data type, which is a special data type used for floating-point numbers with decimal precision. That's not what you need. Your other method, Convert.Hex simply does not exist.

Categories