简体   繁体   中英

Converting string value to hex decimal

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.

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

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") .

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);
}

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM