【问题标题】:PHP: casting to long or unsigned integer with 32 bitsPHP:转换为 32 位长整数或无符号整数
【发布时间】:2011-01-19 15:08:48
【问题描述】:

我有一个 PostgreSQL 8.4.6 表,其中最多 32 张牌的玩家手牌由 32 位表示:

 # \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)

(你可以看到我上面已经用bigint作弊了)。

My script(请滚动到底部查看渲染的卡片)在 64 位 CentOS 5.5 Linux 上运行正常。但是当我将它复制到我的 32 位开发 VM 时,它会失败。

这里是代码摘录:

$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>');
   }

我认为 if ((1 在那里失败(抱歉,如果我不这样做,我稍后会准备一个简化的测试用例'没有收到答案...)

我的问题是:如何在 PHP 中最好地处理这些情况?我需要以某种方式将 $row['hand'] 转换为 unsigned intlong - 以便 AND 位运算符再次工作,但是我在 PHP 文档中找不到这些数据类型。

谢谢!亚历克斯

【问题讨论】:

    标签: php postgresql long-integer unsigned


    【解决方案1】:

    您可以使用GMP 存储号码,然后通过gmp_testbit 测试该卡是否可用。虽然这显然需要安装 GMP(而且它通常不在共享主机上。)

    【讨论】:

    • 请问您实际选择做什么?您是否使用过 GMP 或是否已切换到其他数据结构?还是其他解决方案?
    猜你喜欢
    • 2018-03-23
    • 2019-05-30
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多