modularml / mojo

The Mojo Programming Language
https://docs.modular.com/mojo/manual/
Other
23.15k stars 2.59k forks source link

[Feature Request] Introduce `hex` and `bin` functions that produce fixed-width string output #3671

Open soraros opened 1 week ago

soraros commented 1 week ago

Review Mojo's priorities

What is your request?

As title.

What is your motivation for this change?

In Python, the bin and hex functions return variable-length binary/hexadecimal string representations for int values. Python also follows a convention where negative numbers are represented as -0bXXXX, with XXXX being the binary/hexadecimal representation of the corresponding positive number. This convention primarily makes sense when working with arbitrarily large integers.

Mojo, on the other hand, uses machine integer types, which have well-defined binary/hexadecimal representations (e.g., two's complement for negative numbers). Introducing fixed-width variants of bin and hex functions would not only enhance their utility in low-level programming but also offer a potential performance improvement since the buffer size can be predetermined.

Any other details?

N/A

martinvuyk commented 6 days ago

This will conflict with Python's format spec. We could constraint your proposal to SIMD only, but that would mean also deviating for floats which don't have a separate "independent" type like Int. Another option is to make overloads/use a parameter (default false) to deviate from the format spec.

soraros commented 6 days ago

Come think about it, we could just put them in the bit module.