Following exmaples show conversion between hexadecimal strings and numeric types such as interger.float etc.
Find hexadecimal value of each character in a string:
string str = "Author Code"; char[] strArray = str.ToCharArray(); foreach (char Word in strArray) { int numVal= Convert.ToInt32(Word); string hexaVal = String.Format("{0:X}", numVal); MessageBox.Show("hexadecimal value of " + Word + " is " + hexaVal); }
Make a string from hexadecimal values.
string hexaValues = "41 75 74 68 6F 72 20 43 6F 64"; string[] hexValuesArray = hexaValues.Split(' '); string str=""; foreach (String hexaVal in hexValuesArray) { int numVal = Convert.ToInt32(hexaVal, 16); string stringValue = Char.ConvertFromUtf32(numVal); char charValue = (char)numVal; str += charValue; } MessageBox.Show(str);
Convert a hexadecimal string to an integer
string strHexa = "6F"; int numVal = Int32.Parse(strHexa, System.Globalization.NumberStyles.HexNumber); MessageBox.Show(numVal )
Convert a hexadecimal string to a float
string strHexa = "4560160"; uint numVal = uint.Parse(strHexa, System.Globalization.NumberStyles.AllowHexSpecifier); byte[] floatValArr = BitConverter.GetBytes(numVal); float floatVal = BitConverter.ToSingle(floatValArr, 0);
Convert a decimal to hexadecimal string
int i = 7121; string hexValue = i.ToString("X");
Hi
When I use this article code for convert 7121 to hex, I get 37313231.
But when I use an online convertor then I get “1BD1” for 7121.
What is this Difference ?
Hi Sina
all above code is only for String conversion.
when you convert 7121 to hexadecimal, code assume this number as “7121” string, and convert it to hexadecimal number that is =37313231(it is correct).
I think you have a integer value 7121, Then you can convert it to hexa decimal as:
int i = 7121;
string hexValue = i.ToString(“X”);
You right.
When I convert a value to hex, I must point to my value type.
For integer type we can use Conversion.Hex(). But for string type, We must use a function like yours.
Important thing is that string to hex is so different with integer.