首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言字串轉數值:strtol 多進制解析完全指南

     編輯:關於C語言

為什麼選擇 strtol?

atoi、atol 只支援十進制且無錯誤回報。strtol 是功能最完整的字串轉長整數函數:

  • 支援 2~36 進制(含自動偵測 0x/0 前綴)
  • 提供 endptr 回報解析停止位置,可偵測無效字元
  • 溢位時設定 errno = ERANGE 並回傳 LONG_MAX/MIN

函數原型

#include <stdlib.h>

long int strtol(const char *nptr, char **endptr, int base);
參數說明
nptr待轉換字串,前導空白會被跳過
endptr非 NULL 時,回傳第一個無效字元位址
base進制(2~36 或 0)。0 表示自動偵測:0x→16、0→8、其他→10

實作範例

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main()
{
    char a[] = "100";
    char b[] = "100";
    char c[] = "0x11";
    char d[] = "   -123abc";
    char *pos;
    long x, y, z, w;

    x = strtol(a, NULL, 10);  // 十進制 100
    y = strtol(b, NULL, 2);   // 二進制 100 → 4
    z = strtol(c, NULL, 16);  // 十六進制 0x11 → 17
    w = strtol(d, &pos, 10);  // -123,pos 指向 'a'

    printf("x=%ld, y=%ld, z=%ld, w=%ld\n", x, y, z, w);
    printf("剩餘字串: \"%s\"\n", pos);

    // 錯誤檢查範例
    errno = 0;
    long val = strtol("9999999999999999999", NULL, 10);
    if (errno == ERANGE) printf("溢位!\n");

    return 0;
}

輸出:

x=100, y=4, z=17, w=-123
剩餘字串: "abc"

strtol vs atoi 關鍵差異

特性atoistrtol
進制支援僅 10 進制2~36 進制 + 自動偵測
錯誤回報無(返回 0 無法區分 "0" 與 "abc")endptr + errno
溢位處理未定義行為飽和至 LONG_MAX/MIN + ERANGE
尾隨字元忽略透過 endptr 精確定位

相關函數家族

  • strtoul:轉 unsigned long
  • strtoll / strtoull:C99,轉 64 位元 long long
  • strtof / strtod / strtold:浮點數轉換
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved