开发者

PHP: casting to long or unsigned integer with 32 bits

开发者 https://www.devze.com 2023-02-06 02:05 出处:网络
I have a PostgreSQL 8.4.6 table where player hands with up to 32 cards are represented by 32 bits: # \\d pref_hand

I have a PostgreSQL 8.4.6 table where player hands with up to 32 cards are represented by 32 bits:

 # \d pref_hand
               Table "public.pref_hand"
 Column |            Type             |   Modifiers
--------+-----------------------------+---------------
 id     | character varying(32)       |
 hand   | bigint                      | not null
 money  | integer                     | not null
 stamp  | timestamp without time zone | default now()
Check constraints:
    "pref_hand_hand_check" CHECK (hand > 0)

(you can see that I've already cheated above by using bigint).

My script (please scroll to the bottom to see the rendered cards) works ok on 64-bit CentOS 5.5 Linux. But when I copy it to my 32-bit development VM, it fails.

Here is the code excerpt:

$sth = $db->prepare('select hand, money
                     from pref_hand where id=?
                     order by stamp desc');
$sth->execute(array($id));
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        print ('<div>');
        for ($i = count($CARDS) - 1; $i >= 0; $i--) {
                $card  = $CARDS[$i];
                $color = (strpos($card, '♥') > 0 ||
                          strpos($card, '♦') > 0 ? 'red' : 'black');

                if (23 == $i || 15 == $i || 7 == $i)
                        print('&nbsp;');

                if ((1 << $i) & $row['hand'])
                        printf('<span class="%s">%s</span>', $color, $CARDS[$i]);
        }
        print ('</div>');
   }

and I think the if ((1 << $i) & $row['hand']) is failing there (sorry, I'll prepare a reduced test case later if I don't receive an answer...)

My question is: how to handle those situations be开发者_运维百科st in PHP? I need to cast $row['hand'] to unsigned int or long somehow - so that the AND bit-operator works again, but I can't find those data types in PHP docs.

Thank you! Alex


You may use GMP to store the number and then test if the card is available via gmp_testbit. Though this obviously requires GMP to be installed (and it usually is not on shared hosting.)

0

精彩评论

暂无评论...
验证码 换一张
取 消