By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,481 Members | 1,211 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,481 IT Pros & Developers. It's quick & easy.

Convert 4-byte string to integer

P: n/a
Ive used fwrite to store 4 bytes in a file: "Test" (or 0x54657374 /
1953719636). Its easy enough to use fread to get those 4 bytes, but the
problem is I need to work with the data as a number and not a string, so how
can I convert it to the number 1953719636 ?
Jul 17 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
"Dave Turner" <no****@nowhere.nohow> wrote in message
news:42********@quokka.wn.com.au...
Ive used fwrite to store 4 bytes in a file: "Test" (or 0x54657374 /
1953719636). Its easy enough to use fread to get those 4 bytes, but the
problem is I need to work with the data as a number and not a string, so
how can I convert it to the number 1953719636 ?


http://php.net/unpack
Jul 17 '05 #2

P: n/a
Example please? It doesnt seem to be working ...

<?
$packed = "Test";
$unpacked = unpack("L", $packed);
echo $unpacked;
?>

It should echo 1953719636, but it's not displaying anything

Jul 17 '05 #3

P: n/a
Hmmm, ok :-) Well this works, but it doesnt seem very efficient:

<?
$Buffer = "Test";

$Number = ord($Buffer{0}) | (ord($Buffer{1})<<8) | (ord($Buffer{2})<<16) |
(ord($Buffer{3})<<24);

echo $Number;
?>

If anyone knows of a better method I'd appreciate it, thanks
Jul 17 '05 #4

P: n/a
"Dave Turner" <no****@nowhere.nohow> wrote:
Example please? It doesnt seem to be working ...

<?
$packed = "Test";
$unpacked = unpack("L", $packed);
echo $unpacked;
?>

It should echo 1953719636, but it's not displaying anything


It does work, but you didn't read the docpage well. unpack() returns an
array so use print_r() instead of echo.

E.
Jul 17 '05 #5

P: n/a
> It does work, but you didn't read the docpage well. unpack() returns an
array so use print_r() instead of echo.

Thankyou for clarifying that, "echo $unpacked[1];" also works

So i guess my final question is - what is more efficient? unpack() or 4 x
Ord() ?
Jul 17 '05 #6

P: n/a
"Dave Turner" <no****@nowhere.nohow> wrote:
So i guess my final question is - what is more efficient? unpack() or 4 x
Ord() ?


function utime()
{
list( $usec, $sec ) = explode( ' ', microtime() );
return ((float)$usec + (float)$sec);
}

$t = utime();
for ( $i = 0; $i < 1000000; ++$i )
{
//insert code for testing here
}
$t = utime() - $t;
echo "Time : $t sec\n";
Jul 17 '05 #7

P: n/a
Very useful timing routine, thanks. The unpack/array[1] method is faster by
about 25% over the 4 x ord() method
Jul 17 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.