libstd/type
Conversions between the basic types, in a module that includes nothing else. as converts when nothing is lost (int to long, char to int) and between integers and float (a float becomes an integer truncated toward zero), but it never narrows an integer: this module has the conversions that drop the high bits, text read as a number, digits and hexadecimal. The other direction, number to text, is built into the compiler: itoa(long) and ftoa(float).
#include <libstd/type>
Example
#include <libstd/stdio>
#include <libstd/type>
n = str_to_int("42") + 1 // 43
if str_is_int("12a") == 0:
print("not a number\n")
x = str_to_float("2.5e-1") // 0.25
low = long_to_int(0x100000005 as long) // 5: 'as int' is refused
print(long_to_hex(48879 as long, 6), "\n") // 00beef
Functions
The code of a character, 0–255 (the same as c as int).
The character with code x: keeps the low 8 bits, like the C cast (char).
The low 32 bits of a long, with their sign, like the C cast (int).
The value of a decimal digit ('7' → 7), -1 for any other character.
The value of a hexadecimal digit in either case ('b' and 'B' → 11), -1 otherwise.
The digit for a value from 0 to 15: '0'–'9', then 'a'–'f'.
1 if the whole string is an integer: an optional + or - and at least one digit, nothing else (no spaces). 0 otherwise, also for a null str.
The integer at the start of the string, like C's atol: an optional sign, then digits up to the first other character; 0 if there are none. Past 64 bits it wraps around. str_is_int tells whether the whole string was a number.
str_to_long, keeping the low 32 bits.The hexadecimal number at the start of the string, with an optional 0x or 0X; 0 if there are no digits.
The decimal number at the start of the string, like C's atof: a sign, digits, an optional fraction and exponent ("1.5e-3"); 0.0 if there are no digits. The same result as Python's float() up to 15 significant digits with a power of ten within ±22, the common case; beyond that the relative error stays below 2e-15.
Lowercase hexadecimal without 0x, padded with zeros to at least width digits: long_to_hex(255, 4) is "00ff". A negative value shows all its 64 bits.
Internal helpers
Used by the functions above; not meant to be called directly.
- def pow10_float(e: int) -> float