tags:

views:

352

answers:

4
+2  Q: 

PHP Bytes 2 DWord

I have an array:

$arr[0] = 95
$arr[1] = 8
$arr[2] = 0
$arr[3] = 0

That are bytes. I need a DWORD. I tried:

$dword = $arr[0]+$arr[1]*265+$arr[2]*265*265+$arr[3]*265*265*265;

Is that right or am I doing it wrong?

+3  A: 

Try:

$dword = (($arr[3] & 0xFF) << 24) | (($arr[2] & 0xFF) << 16) | (($arr[1] & 0xFF) << 8) | ($arr[0] & 0xFF);

It can also be done your way with some corrections:

$dword = $arr[0] + $arr[1]*0x100 + $arr[2]*0x10000 + $arr[3]*0x1000000;

Or using pack/unpack:

$dword = array_shift(unpack("L", pack("CCCC", $arr[0], $arr[1], $arr[2], $arr[3])));
Emil H
Thanks that helped
A: 

Or at the very least use 256 rather than 265.

jerryjvl
@Emil, 0xff is 255, so that would be wrong.
driis
Sorry. My bad. :)
Emil H
I have 256 in my code, wrote it wrong here :o. Thx
A: 

Your code should work correctly, but you should multiply with 256, not 265. (in 8 bits, there are 2^8 = 256 unique values). It works, because multiplying with 256 is the same as shifting the bits 8 places to the left.

Perhaps you should consider using the bitwise operators instead, to better convey the intent. See http://theopensourcery.com/phplogic.htm

driis
I have 256 in my code, wrote it wrong here :o. Thx
+1  A: 

Or try

<?php
$arr = array(95,8,0,0);
$bindata = join('', array_map('chr', $arr));
var_dump(unpack('L', $bindata));
both (Emil H's and my code) give you 2143 as the result.

VolkerK
+1. I was thinking of the same way, but wanted to try it first. Added it to my answer just to find that you had already suggested it. :)
Emil H