note 109072 deleted from function.hexdec by danbrown
| From: | danbrown@php.net | Date: | Tue, 19 Jun 2012 01:07:59 +0000 |
| Subject: | note 109072 deleted from function.hexdec by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188681@lists.php.net to get a copy of this message | ||
Note Submitter: sneskid at hotmail dot com
----
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)
?>