簡體   English   中英

將字符串值轉換為十六進制十進制

[英]Converting string value to hex decimal

我在C#中進行應用。 在這種暗示我有包含十進制值作為

string number="12000"; 

相當於12000的十六進制是0x2EE0。

在這里我想將十六進制值分配給整數變量作為

int temp=0x2EE0.

請幫我轉換這個數字。 提前致謝。

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
 */

消息來源: http//msdn.microsoft.com/en-us/library/bb311038.aspx

一個int包含一個數字,而不是數字的表示形式。 12000等效於0x2ee0:

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

您可以使用int.Parse()將字符串“ 12000”轉換為int。 您可以使用int.ToString(“ X”)將int格式化為十六進制。

好吧,您可以使用String.Format類將數字轉換為十六進制

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

如果要將字符串關鍵字轉換為十六進制,則可以執行此操作

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

如果您想將其轉換為十六進制string ,可以通過

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

如果只想將數字作為十六進制。 這是不可能的。 因為計算機總是以二進制格式保存數字,所以當您執行int i = 1000它將1000作為二進制存儲在i 如果您使用十六進制,它將也是二進制的。 所以沒有意義。

您可以嘗試這樣的事情,如果它是int

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM