以主机字节顺序(小端)将字符串转换为网络字节顺序(大端) [英] Convert String in Host byte order (Little endian) to Network byte order (Big endian)
本文介绍了以主机字节顺序(小端)将字符串转换为网络字节顺序(大端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个十六进制字符串,其读取值为 18000000
,该字符串的字节顺序为主机字节顺序(小端),我需要将其转换为网络字节顺序(大端).结果十六进制字符串将为 00000018
.
I have a Hex String which reads 18000000
this String is in Host byte order (Little endian) and I need to convert it to Network byte order (Big endian). The resultant Hex String will be 00000018
.
总结一下,我需要转换 18000000至00000018
如何在PHP中实现此目标?
How do I achieve this in PHP?
推荐答案
您可以使用 pack
/ unpack
函数转换字节序:
You can use pack
/ unpack
functions to convert endianness:
/**
* Convert $endian hex string to specified $format
*
* @param string $endian Endian HEX string
* @param string $format Endian format: 'N' - big endian, 'V' - little endian
*
* @return string
*/
function formatEndian($endian, $format = 'N') {
$endian = intval($endian, 16); // convert string to hex
$endian = pack('L', $endian); // pack hex to binary sting (unsinged long, machine byte order)
$endian = unpack($format, $endian); // convert binary sting to specified endian format
return sprintf("%'.08x", $endian[1]); // return endian as a hex string (with padding zero)
}
$endian = '18000000';
$big = formatEndian($endian, 'N'); // string "00000018"
$little = formatEndian($endian, 'V'); // string "18000000"
To learn more about pack
format take a look at http://www.php.net/manual/en/function.pack.php
这篇关于以主机字节顺序(小端)将字符串转换为网络字节顺序(大端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文