rfc:pack-unpack-float-endianness-modifier

PHP RFC: Add pack()/unpack() endianness modifiers for floating-point numbers

Introduction

This RFC proposes extending the endianness modifier syntax (< and >) to floating-point format codes in PHP's pack() and unpack() functions.

Currently, PHP's pack/unpack functions support floating-point numbers only with machine-dependent byte order:

  • f - single-precision float (4 bytes, machine byte order)
  • d - double-precision float (8 bytes, machine byte order)
  • g/G - single-precision float (little/big endian)
  • e/E - double-precision float (little/big endian)

While PHP already has endian-specific letters for floats (g/G/e/E), the modifier syntax (f</f>/d</d>) provides consistency with the endianness modifier syntax introduced in PHP 8.6.

Perl Specification Reference

According to the Perl documentation (https://perldoc.perl.org/functions/pack), Perl supports endianness modifiers on floating-point format codes:

f<   single-precision float, little-endian byte order
f>   single-precision float, big-endian byte order
d<   double-precision float, little-endian byte order
d>   double-precision float, big-endian byte order

Proposed Solution

This RFC proposes adding endianness modifiers to floating-point format codes:

  • f</f> for single-precision float (4-byte, little/big endian)
  • d</d> for double-precision float (8-byte, little/big endian)

Example usage:

<?php
// little endian
$data = pack('f<d<', 3.14159, 2.71828);
 
// big endian
$data = pack('f>d>', 3.14159, 2.71828);
 
// Unpacking
[$float, $double] = array_values(unpack('f<a/d<b', $data));
?>

Equivalence with Existing Formats:

<?php
pack('f<', 3.14) === pack('g', 3.14);
pack('f>', 3.14) === pack('G', 3.14);
pack('d<', 3.14) === pack('e', 3.14);
pack('d>', 3.14) === pack('E', 3.14);
?>

Error Handling

Modifiers on formats with inherent endianness (g/G and e/E) will emit a ValueError, for example:

<?php
 
pack('g<', 3.14); // ValueError: Endianness modifier '<' cannot be applied to format code 'g' which already has inherent endianness

Backward Incompatible Changes

None. The modifier syntax is opt-in and does not affect existing format strings.

Proposed PHP Version(s)

PHP 8.6 (next minor)

Voting Choices

Yes / No vote requiring 2/3 Yes votes to pass.

Add endianness modifiers to pack()/unpack() for floating-point numbers?
Real name Yes No
Final result: 0 0
This poll has been closed.

References

rfc/pack-unpack-float-endianness-modifier.txt · Last modified: by alexandredaubois