ini_parse_quantity

ini_parse_quantity(string $shorthand): int

PHP 8.2+: parses an ini shorthand value into bytes (the same parser behind memory_limit="128M"); k/M/G suffixes plus 0x/0b/0o/leading-0 bases; unparseable input or an invalid suffix raises E_WARNING and returns a best-effort value.

C C23

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

/* no ini-shorthand parser in the C standard library: hand-roll k/M/G multipliers */
static unsigned long long parse_ini_quantity(const char *text) {
    size_t len = strlen(text);
    char unit = len ? text[len - 1] : '\0';
    unsigned long long mult = 1;
    if (unit == 'k' || unit == 'K') mult = 1024ULL;
    else if (unit == 'm' || unit == 'M') mult = 1024ULL * 1024;
    else if (unit == 'g' || unit == 'G') mult = 1024ULL * 1024 * 1024;
    unsigned long long n = 0;
    size_t digits = mult == 1 ? len : len - 1;
    for (size_t i = 0; i < digits; i++) n = n * 10 + (unsigned long long)(text[i] - '0');
    return n * mult;
}

int main(void) {
    const char *samples[] = {"128M", "1G", "512K", "1024"};
    for (int i = 0; i < 4; i++) {
        printf("%s=%llu\n", samples[i], parse_ini_quantity(samples[i]));
    }
    return 0;
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

C++ C++26

C++26
#include <cctype>
#include <cstdio>
#include <string>

// no ini-shorthand parser in the C++ standard library: hand-roll k/M/G multipliers
static unsigned long long parse_ini_quantity(const std::string &text) {
    char unit = static_cast<char>(std::tolower(static_cast<unsigned char>(text.back())));
    unsigned long long mult = 1;
    if (unit == 'k') mult = 1024ULL;
    else if (unit == 'm') mult = 1024ULL * 1024;
    else if (unit == 'g') mult = 1024ULL * 1024 * 1024;
    unsigned long long n = 0;
    const std::string digits = mult == 1 ? text : text.substr(0, text.size() - 1);
    for (char c : digits) n = n * 10 + static_cast<unsigned long long>(c - '0');
    return n * mult;
}

int main() {
    for (const char *s : {"128M", "1G", "512K", "1024"}) {
        std::printf("%s=%llu\n", s, parse_ini_quantity(s));
    }
    return 0;
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;

static long ParseIniQuantity(string text)
{
    // no ini-shorthand parser in the BCL: hand-roll k/M/G multipliers
    var mult = new Dictionary<string, long> { ["k"] = 1024, ["m"] = 1L << 20, ["g"] = 1L << 30 };
    string unit = text[^1].ToString().ToLowerInvariant();
    if (mult.TryGetValue(unit, out long m))
        return long.Parse(text[..^1]) * m;
    return long.Parse(text);
}

foreach (var s in new[] { "128M", "1G", "512K", "1024" })
{
    Console.WriteLine($"{s}={ParseIniQuantity(s)}");
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strconv"
	"strings"
)

// no ini-shorthand parser in the standard library: hand-roll k/M/G multipliers
func parseIniQuantity(text string) int64 {
	mult := map[string]int64{"k": 1024, "m": 1 << 20, "g": 1 << 30}
	unit := strings.ToLower(text[len(text)-1:])
	if m, ok := mult[unit]; ok {
		n, _ := strconv.ParseInt(text[:len(text)-1], 10, 64)
		return n * m
	}
	n, _ := strconv.ParseInt(text, 10, 64)
	return n
}

func main() {
	for _, s := range []string{"128M", "1G", "512K", "1024"} {
		fmt.Printf("%s=%d\n", s, parseIniQuantity(s))
	}
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

Java v27.0.1

v27.0.1
import java.util.Map;

public class Main {
    // no ini-shorthand parser in the JDK: hand-roll k/M/G multipliers
    static long parseIniQuantity(String text) {
        Map<String, Long> mult = Map.of("k", 1024L, "m", 1L << 20, "g", 1L << 30);
        String unit = text.substring(text.length() - 1).toLowerCase();
        Long m = mult.get(unit);
        if (m != null) return Long.parseLong(text.substring(0, text.length() - 1)) * m;
        return Long.parseLong(text);
    }

    public static void main(String[] args) {
        for (String s : new String[]{"128M", "1G", "512K", "1024"}) {
            System.out.println(s + "=" + parseIniQuantity(s));
        }
    }
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

JavaScript v26.13.1

v26.13.1
// no ini-shorthand parser in the standard library: hand-roll k/M/G multipliers
function parseIniQuantity(text) {
  const mult = { k: 1024, m: 1024 ** 2, g: 1024 ** 3 };
  const unit = text.slice(-1).toLowerCase();
  if (unit in mult) return parseInt(text.slice(0, -1), 10) * mult[unit];
  return parseInt(text, 10);
}
for (const s of ["128M", "1G", "512K", "1024"]) {
  console.log(`${s}=${parseIniQuantity(s)}`);
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

PHP v8.6.0

v8.6.0
// PHP 8.2+: the same shorthand parser behind memory_limit = "128M"
// accepts k/K, m/M, g/G suffixes and 0x/0b/0o/leading-0 bases.
echo ini_parse_quantity('128M'), '/', ini_parse_quantity('1G'), '/', ini_parse_quantity('512K'), "\n";
echo 'bare=', ini_parse_quantity('1024'), '; hex=', ini_parse_quantity('0xFFk'), "\n";
Output
134217728/1073741824/524288
bare=1024; hex=261120

Python v3.15.2

v3.15.2
# no ini-shorthand parser in the standard library: hand-roll k/M/G multipliers
# (int(text, 0) accepts 0x/0b/0o prefixes the same way PHP does)
def parse_ini_quantity(text):
    multipliers = {"k": 1024, "m": 1024 ** 2, "g": 1024 ** 3}
    value = int(text[:-1], 0) if text[-1].lower() in multipliers else int(text, 0)
    return value * multipliers.get(text[-1].lower(), 1)

for short in ("128M", "1G", "512K", "1024"):
    print(short, "=", parse_ini_quantity(short))
Output
128M = 134217728
1G = 1073741824
512K = 524288
1024 = 1024

Rust v1.99.1

v1.99.1
// no ini-shorthand parser in std: hand-roll k/M/G multipliers
fn parse_ini_quantity(text: &str) -> u64 {
    let unit = text.chars().last().unwrap().to_ascii_lowercase();
    let mult = match unit {
        'k' => 1024u64,
        'm' => 1024 * 1024,
        'g' => 1024 * 1024 * 1024,
        _ => 1,
    };
    let digits = if mult == 1 { text } else { &text[..text.len() - 1] };
    digits.parse::<u64>().unwrap() * mult
}

fn main() {
    for s in ["128M", "1G", "512K", "1024"] {
        println!("{s}={}", parse_ini_quantity(s));
    }
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

TypeScript v26.13.1

v26.13.1
// no ini-shorthand parser in the standard library: hand-roll k/M/G multipliers
function parseIniQuantity(text: string): number {
  const mult: Record<string, number> = { k: 1024, m: 1024 ** 2, g: 1024 ** 3 };
  const unit = text.slice(-1).toLowerCase();
  if (unit in mult) return parseInt(text.slice(0, -1), 10) * mult[unit];
  return parseInt(text, 10);
}
for (const s of ["128M", "1G", "512K", "1024"]) {
  console.log(`${s}=${parseIniQuantity(s)}`);
}
Output
128M=134217728
1G=1073741824
512K=524288
1024=1024

Language differences

PHP: added in 8.2 — the official parser that normalizes ini shorthand like memory_limit="128M" into bytes is finally exposed (previously you hand-rolled or copied a polyfill): suffixes k/K=1024, m/M=1024², g/G=1024³; the numeric part accepts decimal, 0x hex, 0b binary, 0o/leading-0 octal (0xFFk=261120, straight from the manual); parse failure or an invalid suffix raises E_WARNING but does NOT throw — no leading digits parse as 0 and an unknown suffix is ignored (backwards-compatible with old ini behavior), so production code must validate on its own; pairs with ini_get/ini_get_all (see those entries): the "128M" string ini_get hands you must go through this function before you can compare it as an int.

C: nothing in the standard library — the example hand-rolls the k/M/G multipliers plus per-character accumulation (a minimal version without overflow guards; production should use strtoull and check ERANGE).

C++: hand-written the same way; cast to unsigned char before std::tolower (avoiding negative-char UB).

C#: nothing built into the BCL (use the .NET ByteSize ecosystem or hand-roll); the example uses a Dictionary plus the range operators text[^1]/text[..^1] for the last character and the tail substring.

Go: nothing built in — strconv.ParseInt plus a hand-written multiplier table (the example); third-party options include github.com/alecthomas/units.

Java: nothing in the JDK — the example uses a Map.of multiplier table plus Long.parseLong; note the L suffix in 1L << 20 prevents int overflow.

JavaScript: nothing built in — the example uses an object-literal multiplier table plus parseInt; there is NO equivalent of int(text, 0), so 0x/0b prefixes need explicit parseInt(text, 16/2).

Python: nothing built in — the example hand-rolls the multiplier table; the highlight is int(text, 0), which natively accepts 0x/0b/0o/leading-0 prefixes (aligning with PHP semantics), one layer less than JS's parseInt.

Rust: nothing in std — the example uses a match multiplier table plus parse::<u64>(); overflow panics (production should use checked_mul/checked_parse).

TypeScript: same as JavaScript; Record<string, number> gives the multiplier table a type signature and the unit in mult narrowing keeps it type-safe.

Teaching anchor: human-friendly quantity shorthands like "128M" are everywhere in config files (php.ini, Docker, Kubernetes resources, systemd), yet only PHP exposes an official parser in its standard library — the other nine all hand-roll a dozen-line multiplier table; two semantic traps recur: k/M/G means the 1024 scale (KiB, not kB), and "invalid suffix silently ignored" differs across implementations — decide both explicitly before writing your own parser.