简体   繁体   English

PHP-字符串到64位数字

[英]PHP - string to 64bit number

I am playing with Twitter API. 我正在使用Twitter API。 Some numbers (like Twitter ID) is really large such as 199693823725682700. 有些数字(例如Twitter ID)确实很大,例如199693823725682700。

I've got this number as string format, and now I need to change it to just normal readable number, not like 1000xE09, because I need to substract -1 from that string-casted number. 我已经将此数字转换为字符串格式,现在我需要将其更改为普通的可读数字,而不是1000xE09,因为我需要从该字符串广播数字中减去-1。 Then, I also need to send the number as string. 然后,我还需要将数字作为字符串发送。

In sum, in PHP, how can I change the string a number, eg, "199693823725682700" to another string "199693823725682699" (original number -1)? 总之,在PHP中,如何将字符串(例如,“ 199693823725682700”)更改为另一个字符串“ 199693823725682699”(原始数字-1)?

Thanks a lot! 非常感谢!

If BCMath is not available (it would be the preferable option if it is available) this function will decrement an arbitrarily sized integer stored as a string. 如果BCMath不可用(如果有的话,它将是更好的选择),此函数将递减存储为字符串的任意大小的整数。 There is no handling for floats or interpolation of scientific notation, it will only work with a string of decimal digits with an optional sign. 没有浮点数或科学计数法插值的处理,仅适用于带有可选符号的十进制数字字符串。

function decrement_string ($str) {

  // 1 and 0 are special cases with this method
  if ($str == 1 || $str == 0) return (string) ($str - 1);

  // Determine if number is negative
  $negative = $str[0] == '-';

  // Strip sign and leading zeros
  $str = ltrim($str, '0-+');

  // Loop characters backwards
  for ($i = strlen($str) - 1; $i >= 0; $i--) {

    if ($negative) { // Handle negative numbers

      if ($str[$i] < 9) {
        $str[$i] = $str[$i] + 1;
        break;
      } else {
        $str[$i] = 0;
      }

    } else { // Handle positive numbers

      if ($str[$i]) {
        $str[$i] = $str[$i] - 1;
        break;
      } else {
        $str[$i] = 9;
      }

    }

  }

  return ($negative ? '-' : '').ltrim($str, '0');

}

See it working 看到它正常工作

Sure. 当然。

BC Math module BC Math模块
Function http://de.php.net/manual/en/function.bcsub.php 函数http://de.php.net/manual/zh/function.bcsub.php

Apparently for now only way to deal with large integers in php is to use the bcmath extension. 显然,目前处理php中大整数的唯一方法是使用bcmath扩展名。 64-bit integers are planed in PHP6. PHP6中计划使用64位整数。

You should try GMP with PHP, 您应该使用PHP尝试GMP,

here is the manual . 这是手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM