Converting string value to hex decimal

风流意气都作罢 提交于 2019-12-29 05:37:11

问题


i am making application in c#. In that implication i have string which contain decimal value as

string number="12000"; 

The Hex equivalent of 12000 is 0x2EE0.

Here i want to assign that hex value to integer variable as

int temp=0x2EE0.

Please help me to convert that number. Thanks in advance.


回答1:


An int contains a number, not a representation of the number. 12000 is equivalent to 0x2ee0:

int a = 12000;
int b = 0x2ee0;
a == b

You can convert from the string "12000" to an int using int.Parse(). You can format an int as hex with int.ToString("X").




回答2:


string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}

/* Output:
   Hexadecimal value of H is 48
    Hexadecimal value of e is 65
    Hexadecimal value of l is 6C
    Hexadecimal value of l is 6C
    Hexadecimal value of o is 6F
    Hexadecimal value of   is 20
    Hexadecimal value of W is 57
    Hexadecimal value of o is 6F
    Hexadecimal value of r is 72
    Hexadecimal value of l is 6C
    Hexadecimal value of d is 64
    Hexadecimal value of ! is 21
 */

SOURCE: http://msdn.microsoft.com/en-us/library/bb311038.aspx




回答3:


Well you can use class String.Format to Convert a Number to Hex

int value = Convert.ToInt32(number);
string hexOutput = String.Format("{0:X}", value);

If you want to Convert a String Keyword to Hex you can do it

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}



回答4:


If you want to convert it to hex string you can do it by

string hex = (int.Parse(number)).ToString("X");

If you want to put only the number as hex. Its not possible. Becasue computer always keeps number in binary format so When you execute int i = 1000 it stores 1000 as binary in i. If you put hex it'll be binary too. So there is no point.




回答5:


you can try something like this if its going to be int

string number = "12000";
int val = int.Parse(number);
string hex = val.ToString("X");


来源:https://stackoverflow.com/questions/8739577/converting-string-value-to-hex-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!