Can someone edit this to look better? Thanks!
I'm trying to have a string that is a Hex value but it is set by a third party (Not The Code Itself) and set it back to an int but still be a Hex value. C# Will let you have an int that is equal to a Hex if you have the 0x in front.
Code:
string HexValue = "0x0FC";
int OtherValue = Convert.ToInt(HexValue);
When I try this I get: 'Input string was not in a correct format.'
You can convert string into a int hex value by adding this System.Globalization.NumberStyles.HexNumber:
string HexValue = "0x0FC";
int OtherValue = int.Parse(HexValue.Substring(2),System.Globalization.NumberStyles.HexNumber);
Hope it helps!
Related
I'm trying to get the actual value of a byte instead of its conversion to an ASCII string.
I have a byte with the value 0x00000073 how do I get 73 as a string value instead of it being converted to the string value of 115?
Andrew Morton is spot on.
If you have byte b = 115; then you want string s = b.ToString("X");
int value = Convert.ToInt32('o');
Byte[] b = new Byte[] { ( byte)value };
File.WriteAllBytes(Default.ProjectsPath , b);
when I open the file it displays o, I want to write the byte value to the file?
Remove the0x then convert:
int i = Convert.ToInt32("0xFE".Substring(2), 16);
Convert.ToInt16(string) will not be able to convert strings that start with '0x', even though that's the correct notation for base 16 numbers. If you want to use your solution, you will need to remove the "0x" from the string conversion. Replace
string s=String.Format("0x{0:X}", value);
with
string s=String.Format("{0:x}", value);
Or you can use Alex K.'s idea and replace
int x=Convert.ToInt16(s);
with
int x=Convert.ToInt16(s.Substring(2));
if you are the one producing the string in the first place then like Alex Barac suggested, dont place a 0x prefix at all... (why create problems you dont need)
if you have to have the prefix, use it... if the prefix is '0x' use
int i = Convert.ToInt32("0xFE".Substring(2), 16); as Alex K. suggested
if it is not '0x', then it probobally a Base10 number:
int i = Convert.ToInt32("342", 10);
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.
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 ;)
hello mates i am trying to store value from dropdown list to an integer but i am getting an exception Input string was not in a correct format.
int experienceYears = Convert.ToInt32("DropDownList1.SelectedValue");
please help.
Remove the quotes; the code as it stands is trying to convert the literal string "DropDownList1.SelectedValue" to an integer, which it can't.
int experienceYears = Convert.ToInt32(DropDownList1.SelectedValue);
Try it without the quotes:
int experienceYears = Convert.ToInt32(DropDownList1.SelectedValue);