468,308 Members | 1,212 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,308 developers. It's quick & easy.

Convert 4-byte string to integer

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
7 9884
"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
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
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
"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
> 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
"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
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.

Similar topics

5 posts views Thread by Omey Samaroo | last post: by
2 posts views Thread by Alberto | last post: by
3 posts views Thread by Thubaiti | last post: by
17 posts views Thread by Terry Jolly | last post: by
2 posts views Thread by kirke | last post: by
reply views Thread by Teichintx | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.