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.
Related
following problem in C# (working in VS Community 2015):
First off, i fairly new to C#, so excuse me if that question would be an easy fix.
I have a contact sensor giving me a string of numbers (length measurement). I read them with the SystemPort Methods and cut them down to the numbers that i need with substring (as the beginning of the string, the "SR00002" is useless to me).
In the end i end up with a string like : "000.3422" or "012.2345". Now i want to convert that string to one solid int-variable that i can work with, meaning subtract values from and such.
Bsp: I want to calculate 012.234 - 000.3422 (or , instead of . but i could change that beforehand)
I already tried Parse and ConvertToInt (while iterating through the string) but the endresult is always a string.
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,");
string b2 = b1[1].Substring(1);
foreach (char c in b2)
{
Convert.ToInt32(c);
}
textBox2.Text = b2 + b2.GetType();
I know that when b2 will be int it can not be printed in the Textbox but ill take care of that later.
When everything is converted accordingly, ill outsource the conversion to its own method =)
The GetType is just for testing and as said shows only System.String (which i dont want). Help would be much appreaciated. I also browsed the searchfunction and google but couldnt find anything of help. I wish any possible helpers a nice day, mfg Chris.
use the int.Parse
int.Parse("123")
You need to assign the converted values to a new variable or array that takes int or other numeric values that you want.
int[] numbers = new int[b1.length];
for(int i = 0; i < b2.length; i++)
{
numbers[i] = Convert.ToInt32(b2[i]);
}
I'm in the process of converting a Delphi app to C#, and I came across this:
alength:=1; //alength is a byte
aa:=astring //astring is a string parameter passed into the function containing all this
alength:=strtoint(copy(aa,2,length(aa)-1));
So copy creates a string from part of an existing string, with the first character of the string starting at index 1, not 0 like other languages. It uses this format:
function copy ( Source : string; StartChar, Count : Integer ) : string;
And then strtoint which converts a string to an int.
For my c# conversion of that bit of code, I have:
alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));
which gives me the error Error 131 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
Since alength is already type byte, I didn't think I had to cast it?
You're using Convert.ToInt32() when you're assigning a byte. Use Convert.ToByte() instead.
Even better would be to use TryParse instead to avoid exceptions when the string isn't valid:
byte alength;
bool success = Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength);
If the parsing succeedded success will be true, otherwise false.
You can define the flow of your program depending on whether the conversion succeeds or not:
byte alength;
if(Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength))
{
//Great success! continue program
}
else
{
//Oops something went wrong!
}
Simply change:
alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));
into
alength = Convert.ToByte(aa.Substring(1 ,aa.Length - 1));
But more important question here would be: what is the range of value for aa string in the original use? Is it 0-255? If it is, then you can simply use ToByte, but if it is not, then you should think of using other data type.
Something like this:
int alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1)); //define as int
The pure cast can also work.
The byte is approx max 255 combinations I belive, so:
byte i = int_variable & 0x000000FF;
Will be fully controled cast.
can use 0xFF because there is no difference & 0x000000FF == 0xFF
I have an integer value. I want to convert it to the Base 64 value. I tried the following code.
byte[] b = BitConverter.GetBytes(123);
string str = Convert.ToBase64String(b);
Console.WriteLine(str);
Its giving the out put as "ewAAAA==" with 8 characters.
I convert the same value to base 16 as follows
int decvalue = 123;
string hex = decvalue.ToString("X");
Console.WriteLine(hex);
the out put of the previous code is 7B
If we do this in maths the out comes are same. How its differ? How can I get same value to Base 64 as well. (I found the above base 64 conversion in the internet)
The question is rather unclear... "How is it differ?" - well, in many different ways:
one is base-16, the other is base-64 (hence they are fundamentally different anyway)
one is doing an arithmetic representation; one is a byte serialization format - very different
one is using little-endian arithmetic (assuming a standard CPU), the other is using big-endian arithmetic
To get a comparable base-64 result, you probably need to code it manually (since Convert only support base-8, base-10, base-16 for arithmetic converts). Perhaps (note: not optimized):
static void Main()
{
string b64 = ConvertToBase64Arithmetic(123);
}
// uint because I don't care to worry about sign
static string ConvertToBase64Arithmetic(uint i)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
StringBuilder sb = new StringBuilder();
do
{
sb.Insert(0, alphabet[(int)(i % 64)]);
i = i / 64;
} while (i != 0);
return sb.ToString();
}
What can be the reason for the problem? My method returns incorrect int values. When I give it hex value of AB or DC or something similar it returns int = 0 but when I give it a hex = 22 it returns me int = 22. (though int should be 34 in this case).
public int StatusBit(int Xx, int Rr) {
int Number;
int.TryParse(GetX(Xx,Rr), out Number);
return Number;
}
I tried to use Number = Convert.ToInt32(GetX(Xx,Rr)); but it gives same result but null instead of 0 for anything that includes letters.
Use Convert.ToInt32(string, int) instead. That way you can give a base the number should be interpreted in. E.g.
return Convert.ToInt32(GetX(Xx, Rr), 16);
(You also don't check the return value of TryParse which would give a hint that the parse failed.)
If you expect both decimal and hexadecimal numbers you need to branch according to how the number looks and use either base 10 or base 16. E.g. if your hexadeximal numbers always start with 0x you could use something along the following lines:
string temp = GetX(Xx, Rr);
return Convert.ToInt32(temp, temp.StartsWith("0x") ? 16 : 10);
But that would depend on how (if at all) you would distinguish the two. If everything is hexadecimal then there is no such need, of course.
Use NumberStyles.HexNumber:
using System;
using System.Globalization;
class Test
{
static void Main()
{
string text = "22";
int value;
int.TryParse(text, NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out value);
Console.WriteLine(value); // Prints 34
}
}
Do you really want to silently return 0 if the value can't be parsed, by the way? If not, use the return value of int.TryParse to determine whether the parsing succeeded or not. (That's the reason it's returning 0 for "AB" in your original code.)
int.TryParse parses a base 10 integer.
Use Convert.ToUInt32(hex, 16) instead
here is my solution;
kTemp = int.Parse(xcc, System.Globalization.NumberStyles.HexNumber);
above kTemp is an integer, and xcc is a string.
xcc can be anything like; FE, 10BA, FE0912... that is to say; xcc is a string of hex characters in any length.
beware; I dont get the 0x prefix with my hex strings.
I have following section of code in my program:
object val;
val = arr[1].Trim(); // in my case i am getting value here is 1.00
now when I am assigning value to a datarow I am getting error
Expected int64 value.
datarow[Convert.ToString(drow["col"]).Trim().ToUpper()] = val;
I am not facing any issue when getting value other that 1.00.
What could be the exact problem? How can I solve it?
Suggestions and solutions are welcome
If that column in your datatable is expecting an Int64 you need to convert val (which is a string) to an Int64:
var val = arr[1].Trim(); // String at this point
long longVal = 0;
if(!long.TryParse(val,out longVal){
throw new InvalidOperationException("value wasnt an Int64!");
}
datarow[Convert.ToString(drow["col"]).Trim().ToUpper()] = longVal
arr[1] seems to be string, and applying .Trim() keeps it as a string, even if it's "1.00". If you need an integer, you need to parse it. However, it can't be parsed to an intteger, because it's actually a double.
As a proof of whether I'm right or not, you can try (Int64)double.Parse(val) and that should work. However, it's up to you to decide whether that's not an issue for your program. There's two possible issues:
val might not be parse-able to double, in which case you will get an exception
val might be a double, but not one that can be represented as an int (too large, or lose precision ex. "1.8" would become 1)
Hope this helps