[英]How to convert this hex string into a long?
我有:“0xE94C827CEB”在十六進制但作為一個字符串。
即:1002011000043(dd mm yyyy HH mm ss)
不幸的是,如果我只有字符串格式,我不知道如何進行轉換,而且我沒有 Convert.ToLong("0xE94C827CEB", 16) 函數,因為我使用的是 .NET Micro Framework(也,沒有可用的 NumberStyles 命名空間。)
有沒有一個函數可以為我轉換這個?
謝謝
我不知道有什么函數可以做到這一點,但我認為您可以通過拆分十六進制字符串並通過 Convert.ToInt32() 傳遞每個部分來非常簡單地做到這一點:
int part1 = Convert.ToInt32("E9", 16)
int part2 = Convert.ToInt32("4C827CEB", 16) //the last 4 bytes
long result = part1 * 4294967296 + part2 //4294967296 being 2^32. Result = 1002011000043
踢它老派並推出你自己的。 這不完全是火箭科學:
public ulong HexLiteral2Unsigned( string hex )
{
if ( string.IsNullOrEmpty(hex) ) throw new ArgumentException("hex") ;
int i = hex.Length > 1 && hex[0]=='0' && (hex[1]=='x'||hex[1]=='X') ? 2 : 0 ;
ulong value = 0 ;
while ( i < hex.Length )
{
uint x = hex[i++] ;
if ( x >= '0' && x <= '9' ) x = x - '0' ;
else if ( x >= 'A' && x <= 'F' ) x = ( x - 'A' ) + 10 ;
else if ( x >= 'a' && x <= 'f' ) x = ( x - 'a' ) + 10 ;
else throw new ArgumentOutOfRangeException("hex") ;
value = 16*value + x ;
}
return value ;
}
使用位移操作符可以清理部分代碼——
static long HexToLong(string hexString)
{
if (!string.IsNullOrWhiteSpace(hexString))
{
hexString = hexString.Trim();
if (hexString.StartsWith("0x"))
hexString = hexString.Substring(2);
if (hexString.Length > 16)
throw new FormatException("Input string is too long");
hexString = hexString.PadLeft(16, '0'); // ensure proper length -- pad the leading zeros
int part1 = Convert.ToInt32(hexString.Substring(0, 8), 16); // first 4 bytes
int part2 = Convert.ToInt32(hexString.Substring(8, 8), 16);//the last 4 bytes
return (part1 << 8 * 4) + part2; // slide it on over -- 8 bits per byte
}
return 0;
}
你去吧
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.