开发者

Swapping bytes of text in PHP

I basically need to port this piece of code to php

for (i = 0; i < 128/4; i++)
    data32[i] = bswap_32(data32[i]);

But, there is no bswap function in php.

Would someone be kind enough to provide me with something that could开发者_JS百科 solve the problem?


This should do it (untested):

function bswap_32($j)
{
    return (($j & 255) << 24) | (($j & 0xff00) << 8) |
           (($j & 0xff0000) >> 8) | (($j & 0xff000000) >> 24);
}

Or, if there is a sign extension problem, this should resolve it:

function bswap_32($j)
{
    return (($j & 255) << 24) | (($j & 0xff00) << 8) |
           (($j & 0xff0000) >> 8) | (255 & (($j & 0xff000000) >> 24));
}


It sounds like bswap_32 is swapping endianness of your 32-bit quantities.

I could just give you some code, but I'd prefer not to do people's work for them, so I'll explain the principle instead:

You can achieve that with bit-shifts and masks (so for instance, you need to mask out the 8 lowest bits, and shift them into the highest 8 bit positions of the result).

Shifting can be done with the << and >> operators. Masking can be done with the & operator. See the PHP manual page on operators for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜