note 109072 added to function.hexdec
| From: | sneskid at hotmail dot com | Date: | Tue, 19 Jun 2012 01:01:35 +0000 |
| Subject: | note 109072 added to function.hexdec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188680@lists.php.net to get a copy of this message | ||
Here is a more flexible version of the shexdec (signed hexdec) function, from an earlier comment.
It has optional offset and length args to make working with long data strings easier & more
optimized.
With the older version you would have to extract the hex portion with substr and pass it to the
function, which then might have run substr again to avoid the sign.
This version can simply merge both substr steps into one, but it always runs substr.
Also supports the '+' sign and checks empty strings to avoid a "Notice: Uninitialized
string offset..." error message.
<?php
/*
* $h : hex string
* $o : optional offset, default 0
* $l : optional length, default 16 (16=64 bit int, 8=32bit int, no need to add 1 for sign)
*/
function shexdec($h,$o=0,$l=16) {
if(!$h){return 0;}
if($h[$o] === '-'){return -('0x'.substr($h,$o+1,$l)+0);}
if($h[$o] === '+'){$o++;}
return ('0x'.substr($h,$o,$l)+0);
}
var_dump(shexdec('')); // int(0)
var_dump(shexdec('-7FFFFFFFFFFFFFFF')); // int(-9223372036854775807)
var_dump(shexdec('+7FFFFFFFFFFFFFFF')); // int(9223372036854775807)
var_dump(shexdec('7FFFFFFFFFFFFFFF')); // int(9223372036854775807)
var_dump(shexdec('foo;-A2;bar;longstring...',4,2)); // int(-162)
?>
----
Server IP: 72.55.140.6
Probable Submitter: 69.159.196.196
----
Manual Page -- http://www.php.net/manual/en/function.hexdec.php
Edit -- https://master.php.net/note/edit/109072
Del: integrated -- https://master.php.net/note/delete/109072/integrated
Del: useless -- https://master.php.net/note/delete/109072/useless
Del: bad code -- https://master.php.net/note/delete/109072/bad+code
Del: spam -- https://master.php.net/note/delete/109072/spam
Del: non-english -- https://master.php.net/note/delete/109072/non-english
Del: in docs -- https://master.php.net/note/delete/109072/in+docs
Del: other reasons-- https://master.php.net/note/delete/109072
Reject -- https://master.php.net/note/reject/109072
Search -- https://master.php.net/manage/user-notes.php