note 77056 added to language.types.integer

From: Date: Mon, 13 Aug 2007 12:33:19 +0000
Subject: note 77056 added to language.types.integer
Groups: php.notes 
Request: Send a blank email to php-notes+get-129441@lists.php.net to get a copy of this message
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters. IP to BIGINT: <?php $ipArr = explode('.',$_SERVER['REMOTE_ADDR']); $ip = $ipArr[0] * 0x1000000 + $ipArr[1] * 0x10000 + $ipArr[2] * 0x100 + $ipArr[3] ; ?> IP as BIGINT read from db back to dotted form: Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so we can enjoy the bitshifts. <?php $ipVal = $row['client_IP']; $ipArr = array(0 => floor( $ipVal / 0x1000000) ); $ipVint = $ipVal-($ipArr[0]*0x1000000); // for clarity $ipArr[1] = ($ipVint & 0xFF0000) >> 16; $ipArr[2] = ($ipVint & 0xFF00 ) >> 8; $ipArr[3] = $ipVint & 0xFF; $ipDotted = implode('.', $ipArr); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 212.179.137.34 ---- Manual Page -- http://www.php.net/manual/en/language.types.integer.php Edit -- https://master.php.net/note/edit/77056 Del: integrated -- https://master.php.net/note/delete/77056/integrated Del: useless -- https://master.php.net/note/delete/77056/useless Del: bad code -- https://master.php.net/note/delete/77056/bad+code Del: spam -- https://master.php.net/note/delete/77056/spam Del: non-english -- https://master.php.net/note/delete/77056/non-english Del: in docs -- https://master.php.net/note/delete/77056/in+docs Del: other reasons-- https://master.php.net/note/delete/77056 Reject -- https://master.php.net/note/reject/77056 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#129441) next »