Current Location: Home> Latest Articles> PHP Integer to Byte Conversion Tutorial: How to Convert int to Byte Array

PHP Integer to Byte Conversion Tutorial: How to Convert int to Byte Array

M66 2025-07-14

PHP Integer to Byte Conversion Tutorial: How to Convert int to Byte Array

In PHP development, you may encounter the need to convert integers to byte format, especially in fields like network programming, encryption algorithms, etc. This article will guide you through how to perform integer-to-byte conversion in PHP and provide a concrete code example.

Key Issues in Byte Conversion

When converting integers to bytes, several important factors need to be considered:

  • Byte Order (Endianness): Different systems may use different byte orders (big-endian or little-endian), which affects how integers are stored in memory.
  • Byte Length: Different data types occupy different byte lengths. You need to choose the appropriate byte array length based on the integer type.
  • Byte Representation: When converting integers to bytes, you may need to consider whether the integer is signed or unsigned, or if padding is required.

Example Code: Converting 32-bit Integer to Byte Array

The following code demonstrates how to convert a 32-bit integer into a byte array:

function intToBytes($num) {
    $bytes = [];
    for ($i = 0; $i < 4; $i++) {
        $bytes[$i] = ($num >> (8 * $i)) & 0xFF;
    }
    return $bytes;
}

$number = 12345; // Integer to be converted
$bytes = intToBytes($number);

echo "Integer $number converted to byte sequence: ";
foreach ($bytes as $byte) {
    echo dechex($byte) . " ";
}

Code Explanation

In the code above, the `intToBytes` function takes an integer as input and converts it into an array of 4 bytes. Using bitwise right shifts and bitwise AND operations, the integer is broken down into individual bytes and arranged in low-to-high order.

In real applications, you may need to handle integers of different bit lengths or adjust for byte order (endianness) depending on the system. This example assumes a 32-bit integer and uses 4 bytes for representation.

Things to Keep in Mind

While the above code demonstrates basic integer-to-byte conversion, you may need more complex handling for different scenarios. For example, consider issues with byte order (big-endian/little-endian) or signed vs unsigned integers.

Conclusion

This article provided a simple PHP code example for converting an integer to byte format. In real development, you can modify and extend this example according to your specific needs to handle more complex scenarios.