在將 VC++ 專案移植到 C# 時,strtoul 是常見的十六進位字串轉無號長整數函式。本文提供完整的對照轉換表、參數對應關係,並針對帶符號/無符號、溢位、異常處理等細節給出最佳實踐。
函式簽名對照
| VC++ (C/C++) | C# 對應 |
unsigned long strtoul(const char *nptr, char **endptr, int base) | ulong Convert.ToUInt64(string, int base) 或 UInt64.TryParse |
strtoul(CT2A(strSrc.Mid(0,2)), &stopstring, 16) | Convert.ToUInt64(strSrc.Substring(0,2), 16) |
核心轉換範例
// VC++ 原始碼
CString strSrc = _T("4F2B");
char *stopstring;
unsigned long val = strtoul(CT2A(strSrc.Mid(0, 2)), &stopstring, 16); // val = 0x4F
// C# 等效寫法(推薦)
string strSrc = "4F2B";
ulong val = Convert.ToUInt64(strSrc.Substring(0, 2), 16); // val = 79 (0x4F)
// 更安全:TryParse 避免例外
if (UInt64.TryParse(strSrc.Substring(0, 2), System.Globalization.NumberStyles.HexNumber, null, out ulong val2))
{
// val2 = 79
}
關鍵差異與避坑點
1. 進制前綴處理
strtoul:base=0 時自動識別 0x/0 前綴
- C#
Convert.ToUInt64:不支援前綴,必須手動移除 0x 或 0
2. 異常行為
| 情況 | strtoul | Convert.ToUInt64 |
| 溢位 | 返回 ULONG_MAX,設 errno=ERANGE | 拋 OverflowException |
| 非法字元 | 停在首個非法字元,endptr 指向該處 | 拋 FormatException |
| 空字串/空指標 | 返回 0,endptr=nptr | 拋 ArgumentNullException/FormatException |
3. 端序與位寬
- VC++
unsigned long 在 32 位系統為 4 bytes,64 位系統為 4/8 bytes(視編譯器)
- C#
ulong 固定 8 bytes(UInt64),uint 固定 4 bytes(UInt32)
- 移植時確認原始碼目標平台位寬,選擇
uint 或 ulong
通用輔助方法(可直接複製)
public static class HexConvert
{
///
/// 模擬 strtoul 行為:支援 0x 前綴、溢位返回 MaxValue、out 參數回傳解析結束位置
///
public static ulong StrToULong(string s, int baseNum, out int endIndex)
{
if (string.IsNullOrEmpty(s)) { endIndex = 0; return 0; }
int start = 0;
if (baseNum == 0 || baseNum == 16)
{
if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ||
s.StartsWith("0X", StringComparison.OrdinalIgnoreCase))
{ start = 2; baseNum = 16; }
else if (s[0] == '0' && s.Length > 1) { start = 1; baseNum = 8; }
else { baseNum = 10; }
}
var clean = s.Substring(start);
if (ulong.TryParse(clean, System.Globalization.NumberStyles.HexNumber, null, out ulong result))
{
endIndex = start + clean.Length;
return result;
}
endIndex = start;
return ulong.MaxValue; // 模擬溢位行為
}
}
// 使用
int endPos;
ulong v = HexConvert.StrToULong("0x4F2B", 0, out endPos); // v=20267, endPos=6
快速對照表
| VC++ 代碼 | C# 代碼 | 備註 |
strtoul(s, &end, 16) | Convert.ToUInt64(s, 16) | 無前綴 |
strtoul(s, &end, 0) | HexConvert.StrToULong(s, 0, out end) | 自動識別前綴 |
strtoul(s, NULL, 10) | ulong.Parse(s) | 純十進位 |
strtoull (64-bit) | Convert.ToUInt64 | 同樣對應 ulong |
掌握上述對照與輔助方法,即可無縫完成 strtoul 從 C++ 到 C# 的移植,並正確處理邊界情況。
- 上一篇文章: VirtualBox Host-Only 模式下 Win7 主機與客戶機無法互 Ping 解決辦法
- 下一篇文章: Ubuntu 終端多標籤自動 SSH 登入腳本實戰
Copyright ©
程式碼之家 All Rights Reserved