Convert String in Host byte order (Little endian) to Network byte order (Big endian)

谁说胖子不能爱 提交于 2021-01-29 03:03:17

问题


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.

To summarize I need to convert 18000000 to 00000018

How do I achieve this in PHP?


回答1:


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




回答2:


another way

$input = 18000000;  

$length=strlen((string)$input);
$sum=0;
$numbers="";
while ($length>0) {     
    $number = $input % 10;
    $numbers.= $number;        
    $input = $input/10;
    $length--;
}
echo $numbers;



回答3:


I just stumbled on this answer while searching for something, but I ended up doing something a lot simpler (since I knew my string was always going to have a leading zero if necessary to align to a two character boundary):

$littlendian = join(array_reverse(str_split($bigendian), 2)));

Obviously if your bigendian input isn't well formatted like that, this trick isn't going to work directly :)




回答4:


Try this:

$result=bin2hex( implode( array_reverse( str_split( hex2bin($src) ) ) ) );


来源:https://stackoverflow.com/questions/40828024/convert-string-in-host-byte-order-little-endian-to-network-byte-order-big-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!