Building a binary 'string' with PHP

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • CptDondo

    Building a binary 'string' with PHP

    I am working with a communications protocol that requires me to pack an
    array of integers into a binary 'string'.

    Let's say I have this:

    int[0] = 0x1234
    int[2] = 0x5678
    int[3] = 0x9abc
    int[4] = 0xdef0

    I have to produce a string containing

    0x 12 34 56 78 9a bc de f0

    and send it off. The string contains the ints packed together in
    big-endian order: HI LO HI LO HI LO.

    In C, I can do this pretty easily, but I am not familiar enough with
    PHP's data handling. I don't even know where to begin.

    I know PHP can do it, since it handles images but how do you build
    something like this from scratch? How can you build a string byte by byte?

    --Yan
  • petersprc

    #2
    Re: Building a binary 'string' with PHP

    Try pack('n*', 0x1234, 0x5678, 0x9abc, 0xdef0)

    CptDondo wrote:
    I am working with a communications protocol that requires me to pack an
    array of integers into a binary 'string'.
    >
    Let's say I have this:
    >
    int[0] = 0x1234
    int[2] = 0x5678
    int[3] = 0x9abc
    int[4] = 0xdef0
    >
    I have to produce a string containing
    >
    0x 12 34 56 78 9a bc de f0
    >
    and send it off. The string contains the ints packed together in
    big-endian order: HI LO HI LO HI LO.
    >
    In C, I can do this pretty easily, but I am not familiar enough with
    PHP's data handling. I don't even know where to begin.
    >
    I know PHP can do it, since it handles images but how do you build
    something like this from scratch? How can you build a string byte by byte?
    >
    --Yan

    Comment

    Working...