So i'm making a class in PHP to parse the VPK file format.
However i've hit a problem:
object(VPKHeader)#2 (3) {
["Signature"]=>
string(8) "3412aa55"
["Version"]=>
string(4) "1000"
["DirectoryLength"]=>
int(832512)
}
The signature is supposed to be 0x55aa1234, however the signature I'm reading is 0x3412aa55.
How do I switch the endianness in PHP?
If your hex values will always be strings, you can use the following function :
function swapEndianness($hex) {
return implode('', array_reverse(str_split($hex, 2)));
}
Agreed, it's not the most efficient, but the code is quite elegant in my opinion. Also, it works with all sizes of numbers.
You have to convert the value manually. The algorithm will be the same as it is in C++, so just port this code (you only need the one that works on int
afaik):
inline void endian_swap(unsigned short& x)
{
x = (x>>8) |
(x<<8);
}
// this is the one you need
inline void endian_swap(unsigned int& x)
{
x = (x>>24) |
((x<<8) & 0x00FF0000) |
((x>>8) & 0x0000FF00) |
(x<<24);
}
// __int64 for MSVC, "long long" for gcc
inline void endian_swap(unsigned __int64& x)
{
x = (x>>56) |
((x<<40) & 0x00FF000000000000) |
((x<<24) & 0x0000FF0000000000) |
((x<<8) & 0x000000FF00000000) |
((x>>8) & 0x00000000FF000000) |
((x>>24) & 0x0000000000FF0000) |
((x>>40) & 0x000000000000FF00) |
(x<<56);
}
Source: http://www.codeguru.com/forum/showthread.php?t=292902
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With