hexdec

hexdec(string $hex_string): int|float

十六进制字符串转换为十进制数。

C C23

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

int main(void) {
    const char *hexes[] = {"ff", "7ea", "fff"};
    for (int i = 0; i < 3; i++) {
        printf("%ld\n", strtol(hexes[i], NULL, 16));
    }
    return 0;
}
输出
255
2026
4095

C++ C++26

C++26
#include <iostream>
#include <string>
int main() {
    for (const std::string s : {"ff", "7ea", "fff"}) {
        std::cout << std::stoi(s, nullptr, 16) << "\n";
    }
    return 0;
}
输出
255
2026
4095

C# v11.0.100

v11.0.100
foreach (var s in new[] { "ff", "7ea", "fff" }) {
    Console.WriteLine(Convert.ToInt32(s, 16));
}
输出
255
2026
4095

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "strconv"
)

func main() {
    for _, s := range []string{"ff", "7ea", "fff"} {
        n, err := strconv.ParseInt(s, 16, 64)
        if err != nil {
            panic(err)
        }
        fmt.Println(n)
    }
}
输出
255
2026
4095

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        for (String s : new String[]{"ff", "7ea", "fff"}) {
            System.out.println(Integer.parseInt(s, 16));
        }
    }
}
输出
255
2026
4095

JavaScript v26.13.1

v26.13.1
console.log(parseInt("ff", 16));
console.log(parseInt("7ea", 16));
console.log(parseInt("fff", 16));
输出
255
2026
4095

PHP v8.6.0

v8.6.0
echo hexdec("ff"), "\n", hexdec("7ea"), "\n", hexdec("fff");
输出
255
2026
4095

Python v3.15.2

v3.15.2
print(int("ff", 16))
print(int("7ea", 16))
print(int("fff", 16))
输出
255
2026
4095

Rust v1.99.1

v1.99.1
fn main() {
    for s in ["ff", "7ea", "fff"] {
        let n = i64::from_str_radix(s, 16).unwrap();
        println!("{n}");
    }
}
输出
255
2026
4095

TypeScript v26.13.1

v26.13.1
const hex: string = "7ea";
console.log(parseInt("ff", 16));
console.log(parseInt(hex, 16));
console.log(parseInt("fff", 16));
输出
255
2026
4095

语言差异说明

C:strtol(s, NULL, 16);停在首个非法字符处(不报错,可查 endptr);接受 0x 前缀。

C++:std::stoi(s, nullptr, 16);前缀解析(读到非法处为止);接受 0x 前缀。

C#:Convert.ToInt32(s, 16);严格抛错;不接受 0x 前缀。

Go:strconv.ParseInt(s, 16, 64);严格抛错;base=16 不接受 0x 前缀(想要前缀解析用 base=0)。

Java:Integer.parseInt(s, 16);严格抛错(NumberFormatException);不接受 0x 前缀;限 32 位(大数用 Long.parseLong)。

JavaScript:parseInt(s, 16);前缀解析;接受 0x 前缀。

PHP:十六进制字符串→十进制整数,示例输出全一致——hexdec;对非法字符的态度差异最大:跳过非十六进制字符再拼(hexdec("0xFF") 仍得 255,垃圾进好果出);范围:结果超过 int 上限返回 float。

Python:int(s, 16);严格抛错(ValueError);接受 0x 前缀。

Rust:i64::from_str_radix(s, 16);严格抛错(Err);不接受 0x 前缀。

TypeScript:同 JavaScript,parseInt(s, 16)。