在c#中将字符串(十六进制格式)复制到ulong

时间:2015-04-20 08:35:45

标签: c# .net

我需要将十六进制格式的字符串元素复制到ulong。

示例:

string s = "0x4E45565251554954";     // already in hex format

ulong t;     // this ulong should be t=0x4E45565251554954.

2 个答案:

答案 0 :(得分:3)

或者:

string s = "0x4E45565251554954";
ulong t = Convert.ToUInt64(s, 16);

答案 1 :(得分:1)

这里有一些指示......我担心转换并不像你希望的那么简单......

Taken from here.

即。它是签名还是未签名的值?

“执行二进制操作或数字转换时,开发人员始终有责任验证方法或操作符是否使用适当的数字表示来解释特定值。以下示例说明了确保方法的一种技术在将十六进制字符串转换为UInt64值时,不会不恰当地使用二进制表示来解释使用二进制补码表示的值。该示例确定值在将该值转换为其字符串表示形式时是表示有符号整数还是无符号整数。该示例将值转换为UInt64值,它检查原始值是否为有符号整数。如果是,并且如果设置了其高位(表示原始值为负),则该方法抛出异常。 “

// Create a negative hexadecimal value out of range of the UInt64 type. 
long sourceNumber = Int64.MinValue;
bool isSigned = Math.Sign((long)sourceNumber.GetType().GetField("MinValue").GetValue(null)) == -1;
string value = Convert.ToString(sourceNumber, 16);
UInt64 targetNumber;
try
{
   targetNumber = Convert.ToUInt64(value, 16);
   if (isSigned && ((targetNumber & 0x8000000000000000) != 0))
      throw new OverflowException();
   else 
      Console.WriteLine("0x{0} converts to {1}.", value, targetNumber);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned long integer.", 
                 value);
} 

// Displays the following to the console: 
//    Unable to convert '0x8000000000000000' to an unsigned long integer.   

以下示例尝试将数字字符串数组中的每个元素解释为十六进制值,并将其转换为无符号长整数。

public class Example
{
   public static void Main()
   {
      string[] hexStrings = { "80000000", "0FFFFFFF", "F0000000", "00A3000", "D", 
                          "-13", "9AC61", "GAD", "FFFFFFFFFF" };

      foreach (string hexString in hexStrings)
      {
         Console.Write("{0,-12}  -->  ", hexString);
         try {
            uint number = Convert.ToUInt32(hexString, 16);
            Console.WriteLine("{0,18:N0}", number);
         }
         catch (FormatException) {
            Console.WriteLine("{0,18}", "Bad Format");
         }   
         catch (OverflowException)
         {
            Console.WriteLine("{0,18}", "Numeric Overflow");
         }   
         catch (ArgumentException) {
            Console.WriteLine("{0,18}", "Invalid in Base 16");
         }
      }                                            
   }
}
// The example displays the following output: 
//       80000000      -->       2,147,483,648 
//       0FFFFFFF      -->         268,435,455 
//       F0000000      -->       4,026,531,840 
//       00A3000       -->             667,648 
//       D             -->                  13 
//       -13           -->  Invalid in Base 16 
//       9AC61         -->             633,953 
//       GAD           -->          Bad Format 
//       FFFFFFFFFF    -->    Numeric Overflow