Reading A Long From A File After Parsing [C#] - c#

I am trying to read from a file that is structured as such:
VariableName:14326A6AC
Value:Long
Value:Long
I am trying to read it doing it as listed below, but I get a format error. When I add the formatting for hexadecimal (the format the longs are in) they are converted to decimal. Is there a way to keep them as a long so I don't have to do the long conversion from decimal to hex?
public static long returnLineValue(string lineName)
{
var lines = File.ReadLines(filePath);
foreach (var line in lines)
{
if (line != null)
{
char split = ':';
if(line.Contains(lineName))
{
string[] s = line.Split(split);
return Int64.Parse(s[1]);
}
}
}
return 0;
}

This is what you need:
return Convert.ToInt64(s[1], 16)
16 is base 16 (hexadecimal). This function convert from a hexadecimal string to a long.

You have to allow hexadecimal values in Parse:
...
// The same Parse but with hexadecimals allowed
return Int64.Parse(s[1], NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
...
whenever you want to represent Int64 in hexadecimal form, use formatting:
Int64 value = 255;
String result = value.ToString("X"); // "X" for hexadeimal, capital letters
// "FF"
Console.Write(result);

Try this
return Int64.Parse(s[1],System.Globalization.NumberStyles.HexNumber)

Related

ulong.Parse(string, NumberStyles) Exception C#

i been working on this "string to Binary" method for longer than usual and i have no idea where i m going wrong.
i have already searched the internet for solution but nothing seem to be working the way it supposed to do.
public static string hexToBin(string strValue)
{
byte[] hexThis = ASCIIEncoding.ASCII.GetBytes(strValue.ToString());
string thiI = ToHex(strValue);
ulong number = UInt64.Parse(*string*, System.Globalization.NumberStyles.HexNumber);
byte[] bytes = BitConverter.GetBytes(number);
string binaryString = string.Empty;
foreach (byte singleByte in bytes)
{
binaryString += Convert.ToString(singleByte, 2);
}
return binaryString;
}
ToHex(string) takes string and returns its hex representation.
but all i keep getting is "Input string was not in a correct format." at the ulong.Parse(string, NumberStyle); and no matter what are my inputs i keep getting the "FormatException" "Input string was not in a correct format." Error.
the inputs and its outputs
string: format exception - "Hello"
hex: format exception - "48 65 6C 6C 6F"
byte[]: format exception - { 72, 101, 108, 108, 111 }
i have also tried using the "Hello" string, but it threw me the same error.
would you please let me know what i m doing wrong in here?
i also have tried "Clean/build/rebuild" restart visual studio, but i keep getting the same format exception.
EDIT,, used UInt64.Parse() not ulong.Parse() and the used string is "Hello" w/o quotation.
EDIT #2,,
so i did this based on knittl suggestion and used the Convert.ToUInt64 instead of the parse, but still getting same error
ulong binary;
string binThis;
byte[] ByteThis;
binThis = "Hello";
ByteThis = ASCIIEncoding.ASCII.GetBytes(binThis);
binary = Convert.ToUInt64(ByteThis);
Console.WriteLine(binary);
the CurrentCulture is set to en-US and i m also using en-US keyboard
EDIT #3 - Solved
thanks to knittl
the solution is as follow:
string thestring = "example";
string[] finale = new string[thestring.Length];
foreach (var c in ByteThis)
{
for (int i = 0; i < ByteThis.Length; i++)
{
thestring = Convert.ToString(c, 2);
thestring = "0" + thestring;
if (thestring.Length == 9)
thestring.Remove(0, 1);
finale[i] = thestring;
Console.WriteLine(finale[i]);
}
}
the final for is to check on the solution.
this question aimed to get the binary representation of a given string.
Not totally clear, what your method should do (i.e. what format the input string is. Is it a bas10 number, or already a hexadecimal number?)
If it's a hexadecimal number, use ulong.Parse(inputStr, NumberStyles.HexNumber). If not, simply use ulong.Parse(inputStr). Note that NumberStyles.HexNumber does not allow the 0x prefix (Convert.ToUInt64(inputStr) does however).
Then, once you have your input string parsed to a number, simply use Convert.ToString(number, 2) to convert to base2. You will notice that there is no overload which takes an ulong and an int, but you can simply cast your number to a (signed) long, since the binary representation will be identical between the two (cf. two's complement). So, in effect Convert.ToString((long)number, 2).
No need for complicated loops and conversions to byte arrays.
Bonus answer.
If you are not too concerned with performance, you can even use a LINQ one-liner:
Encoding.ASCII.GetBytes(inputStr).Aggregate(
new StringBuilder(),
(sb, ch) => sb.Append(Convert.ToString(ch, 2).PadLeft(8, '0')),
sb => sb.ToString());

How to UNHEX() MySQL binary string in C# .NET?

I need to use HEX() in MySQL to get data out of the database and process in C# WinForm code. The binary string needs to be decoded in C#, is there an equivalent UNHEX() function?
From MySQL Doc:
For a string argument str, HEX() returns a hexadecimal string
representation of str where each byte of each character in str is
converted to two hexadecimal digits. (Multi-byte characters therefore
become more than two digits.) The inverse of this operation is
performed by the UNHEX() function.
For a numeric argument N, HEX() returns a hexadecimal string
representation of the value of N treated as a longlong (BIGINT)
number. This is equivalent to CONV(N,10,16). The inverse of this
operation is performed by CONV(HEX(N),16,10).
mysql> SELECT 0x616263, HEX('abc'), UNHEX(HEX('abc'));
-> 'abc', 616263, 'abc' mysql> SELECT HEX(255), CONV(HEX(255),16,10);
-> 'FF', 255
You can use this not-widely-known SoapHexBinary class to parse hex string
string hex = "616263";
var byteArr = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(hex).Value;
var str = Encoding.UTF8.GetString(byteArr);
After fetching the binary string from the database, you can "unhex" it this way:
public static string Hex2String(string input)
{
var builder = new StringBuilder();
for(int i = 0; i < input.Length; i+=2){ //throws an exception if not properly formatted
string hexdec = input.Substring(i, 2);
int number = Int32.Parse(hexdec, NumberStyles.HexNumber);
char charToAdd = (char)number;
builder.Append(charToAdd);
}
return builder.ToString();
}
The method builds a string from the hexadecimal format of the numbers, their char representation being concatenated to the builder branch.

Convert ASCII to HEX keeping line breaks

OK so I'm making a ASCII to HEX converter and it works fine, but when i insert line breaks it replaces them with this character -> Ú
ie
turns this
1
2
3
to this
1Ú2Ú3
Code under command buttons
private void asciiToHex_Click(object sender, EventArgs e)
{
HexConverter HexConvert =new HexConverter();
string sData=textBox1.Text;
textBox2.Text = HexConvert.StringToHexadecimal(sData);
}
private void hexToAscii_Click(object sender, EventArgs e)
{
HexConverter HexConvert = new HexConverter();
string sData = textBox1.Text;
textBox2.Text = HexConvert.HexadecimalToString(sData);
}
Code under HexConverter.cs
public class HexConverter
{
public string HexadecimalToString(string Data)
{
string Data1 = "";
string sData = "";
while (Data.Length > 0)
//first take two hex value using substring.
//then convert Hex value into ascii.
//then convert ascii value into character.
{
Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();
sData = sData + Data1;
Data = Data.Substring(2, Data.Length - 2);
}
return sData;
}
public string StringToHexadecimal(string Data)
{
//first take each charcter using substring.
//then convert character into ascii.
//then convert ascii value into Hex Format
string sValue;
string sHex = "";
foreach (char c in Data.ToCharArray())
{
sValue = String.Format("{0:X}", Convert.ToUInt32(c));
sHex = sHex + sValue;
}
return sHex;
}
}
Any Ideas?
The problem is that String.Format("{0:X}", Convert.ToUInt32(c)) does not zero-pad its output to two digits, so \r\n becomes DA instead of 0D0A. You'll get a similar problem, but worse, with \t (which becomes 9 instead of 09, which will cause misalignment for subsequent characters as well).
To zero-pad to two digits, you can use X2 instead of bare X; or, more generally, you can use Xn to zero-pad to n digits. (See the "Standard Numeric Format Strings" page on MSDN.)
Instead of
System.Convert.ToUInt32(hexString), use
uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
MSDN says the "AllowHexSpecifier flag indicates that the string to be parsed is always interpreted as a hexadecimal value"
How to: Convert Between Hexadecimal Strings and Numeric Types
the laziest thing you could do is do a string.replace("Ú","\r\n") on the result. Unless there were a compelling reason not to do it this way, I would start here.
Otherwise, in your Char loop, look for the NewLine char and add it as-is to your string.

Parse string and return only the information between bracket symbols. C# Winforms

I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.
Hopefully I have provided sufficient information.
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
Why not use Regex?
In this example, I am assuming that your value inside the brackets always are a double with decimals.
string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
If you can ensure that the content between the brackets is of the form <decimal>%, then this little function will return the value between the fist set of brackets. If there are more than one values you need to extract then you will need to modify it somewhat.
public decimal getProp(string str)
{
int obIndex = str.IndexOf("["); // get the index of the open bracket
int cbIndex = str.IndexOf("]"); // get the index of the close bracket
decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
return Math.Round(d); // return the number rounded to the nearest integer
}
For example getProp("I like cookies [66.7%]") gives the Decimal number 67
Use regular expressions (Regex) to find the required words within one bracket.
This is the code you need:
Use an foreach loop to remove the % and convert to int.
List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, #"\[(?<tag>[^\]]*)\]")){
s = s.TrimEnd('%');
myValues.Add(Math.Round(Convert.ToDouble(s)));
}

How to convert a regular string to an ASCII hexadecimal string in C#?

I was recently working on a project where I needed to convert a regular string of numbers into ASCIII hexadecimal and store the hex in a string.
So I had something like
string random_string = "4000124273218347581"
and I wanted to convert it into a hexadecimal string in the form
string hex_string = "34303030313234323733323138333437353831"
This might seem like an oddly specific task but it's one I encountered and, when I tried to find out how to perform it, I couldn't find any answers online.
Anyway, I figured it out and created a class to make things tidier in my code.
In case anyone else needs to convert a regular string into a hexadecimal string I'll be posting an answer in a moment which will contain my solution.
(I'm fairly new to stackoverflow so I hope that doing this is okay)
=========================================
Turns out I can't answer my question myself within the first 8 hours of asking due to not having a high enough reputation.
So I'm sticking my answer here instead:
Okay, so here's my solution:
I created a class called StringToHex in the namespace
public class StringToHex
{
private string localstring;
private char[] char_array;
private StringBuilder outputstring = new StringBuilder();
private int value;
public StringToHex(string text)
{
localstring = text;
}
public string ToAscii()
{
/* Convert text into an array of characters */
char_array = localstring.ToCharArray();
foreach (char letter in char_array)
{
/* Get the integral value of the character */
value = Convert.ToInt32(letter);
/* Convert the decimal value to a hexadecimal value in string form */
string hex = String.Format("{0:X}", value);
/* Append hexadecimal version of the char to the string outputstring*/
outputstring.Append(Convert.ToString(hex));
}
return outputstring.ToString();
}
}
And to use it you need to do something of the form:
/* Convert string to hexadecimal */
StringToHex an_instance_of_stringtohex = new StringToHex(string_to_convert);
string converted_string = an_instance_of_stringtohex.ToAscii();
If it's working properly, the converted string should be twice the length of the original string (due to hex using two bytes to represent each character).
Now, as someone's already pointed out, you can find an article doing something similar here:
http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx
But I didn't find it much help for my specific task and I'd like to think that my solution is more elegant ;)
This works as long as the character codes in the string is not greater than 255 (0xFF):
string hex_string =
String.Concat(random_string.Select(c => ((int)c).ToString("x2")));
Note: This also works for character codes below 16 (0x10), e.g. it will produce the hex codes "0D0A" from the line break characters "\r\n", not "DA".
you need to read the following article -
http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx
the main function that converts data into hex format
public string Data_Hex_Asc(ref string Data)
{
string Data1 = "";
string sData = "";
while (Data.Length > 0)
//first take two hex value using substring.
//then convert Hex value into ascii.
//then convert ascii value into character.
{
Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();
sData = sData + Data1;
Data = Data.Substring(2, Data.Length - 2);
}
return sData;
}
see if this what you are looking for.
Okay, so here's my solution:
I created a class called StringToHex in the namespace
public class StringToHex
{
private string localstring;
private char[] char_array;
private StringBuilder outputstring = new StringBuilder();
private int value;
public StringToHex(string text)
{
localstring = text;
}
public string ToAscii()
{
/* Convert text into an array of characters */
char_array = localstring.ToCharArray();
foreach (char letter in char_array)
{
/* Get the integral value of the character */
value = Convert.ToInt32(letter);
/* Convert the decimal value to a hexadecimal value in string form */
string hex = String.Format("{0:X}", value);
/* Append hexadecimal version of the char to the string outputstring*/
outputstring.Append(Convert.ToString(hex));
}
return outputstring.ToString();
}
}
And to use it you need to do something of the form:
/* Convert string to hexadecimal */
StringToHex an_instance_of_stringtohex = new StringToHex(string_to_convert);
string converted_string = an_instance_of_stringtohex.ToAscii();
If it's working properly, the converted string should be twice the length of the original string (due to hex using two bytes to represent each character).
Now, as someone's already pointed out, you can find an article doing something similar here:
http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx
But I didn't find it much help for my specific task and I'd like to think that my solution is more elegant ;)

Categories